blob: 33574b9aec35afd7fd93e261fc6236d8a2927779 [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035#include <algorithm>
David Blaikie8ad22e62014-05-01 23:01:41 +000036#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000037
Richard Smith17c00b42014-11-12 01:24:00 +000038using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000039using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000040
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000041static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
George Burgess IV21081362016-07-24 23:12:40 +000042 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43 return P->hasAttr<PassObjectSizeAttr>();
44 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000045}
46
Nick Lewycky134af912013-02-07 05:08:22 +000047/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000048static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000049CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000051 SourceLocation Loc = SourceLocation(),
52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000053 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000054 return ExprError();
55 // If FoundDecl is different from Fn (such as if one is a template
56 // and the other a specialization), make sure DiagnoseUseOfDecl is
57 // called on both.
58 // FIXME: This would be more comprehensively addressed by modifying
59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60 // being used.
61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000062 return ExprError();
Richard Smith5f4b3882016-10-19 00:14:23 +000063 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64 S.ResolveExceptionSpec(Loc, FPT);
John McCall113bee02012-03-10 09:33:50 +000065 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000066 VK_LValue, Loc, LocInfo);
67 if (HadMultipleCandidates)
68 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000069
70 S.MarkDeclRefReferenced(DRE);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000071 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000073}
74
John McCall5c32be02010-08-24 20:38:10 +000075static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000077 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000078 bool CStyle,
79 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000080
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000081static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
82 QualType &ToType,
83 bool InOverloadResolution,
84 StandardConversionSequence &SCS,
85 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000086static OverloadingResult
87IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88 UserDefinedConversionSequence& User,
89 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000090 bool AllowExplicit,
91 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000092
93
94static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000095CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000096 const StandardConversionSequence& SCS1,
97 const StandardConversionSequence& SCS2);
98
99static ImplicitConversionSequence::CompareKind
100CompareQualificationConversions(Sema &S,
101 const StandardConversionSequence& SCS1,
102 const StandardConversionSequence& SCS2);
103
104static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000105CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000106 const StandardConversionSequence& SCS1,
107 const StandardConversionSequence& SCS2);
108
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109/// GetConversionRank - Retrieve the implicit conversion rank
110/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000111ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000112 static const ImplicitConversionRank
113 Rank[(int)ICK_Num_Conversion_Kinds] = {
114 ICR_Exact_Match,
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Exact_Match,
118 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000119 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000120 ICR_Promotion,
121 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000122 ICR_Promotion,
123 ICR_Conversion,
124 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000125 ICR_Conversion,
126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000130 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000131 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000132 ICR_Conversion,
133 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000134 ICR_Complex_Real_Conversion,
135 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000136 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000137 ICR_Writeback_Conversion,
138 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139 // it was omitted by the patch that added
140 // ICK_Zero_Event_Conversion
George Burgess IV2099b542016-09-02 22:59:57 +0000141 ICR_C_Conversion,
142 ICR_C_Conversion_Extension
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000143 };
144 return Rank[(int)Kind];
145}
146
147/// GetImplicitConversionName - Return the name of this kind of
148/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000149static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000150 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 "No conversion",
152 "Lvalue-to-rvalue",
153 "Array-to-pointer",
154 "Function-to-pointer",
Richard Smith3c4f8d22016-10-16 17:54:23 +0000155 "Function pointer conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000156 "Qualification",
157 "Integral promotion",
158 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000159 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 "Integral conversion",
161 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000162 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000163 "Floating-integral conversion",
164 "Pointer conversion",
165 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000166 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000167 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000168 "Derived-to-base conversion",
169 "Vector conversion",
170 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000171 "Complex-real conversion",
172 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000173 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000174 "Writeback conversion",
175 "OpenCL Zero Event Conversion",
George Burgess IV2099b542016-09-02 22:59:57 +0000176 "C specific type conversion",
177 "Incompatible pointer conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000178 };
179 return Name[Kind];
180}
181
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000182/// StandardConversionSequence - Set the standard conversion
183/// sequence to the identity conversion.
184void StandardConversionSequence::setAsIdentityConversion() {
185 First = ICK_Identity;
186 Second = ICK_Identity;
187 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000188 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000189 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000190 ReferenceBinding = false;
191 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000192 IsLvalueReference = true;
193 BindsToFunctionLvalue = false;
194 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000195 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000196 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000197 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000198}
199
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000200/// getRank - Retrieve the rank of this standard conversion sequence
201/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202/// implicit conversions.
203ImplicitConversionRank StandardConversionSequence::getRank() const {
204 ImplicitConversionRank Rank = ICR_Exact_Match;
205 if (GetConversionRank(First) > Rank)
206 Rank = GetConversionRank(First);
207 if (GetConversionRank(Second) > Rank)
208 Rank = GetConversionRank(Second);
209 if (GetConversionRank(Third) > Rank)
210 Rank = GetConversionRank(Third);
211 return Rank;
212}
213
214/// isPointerConversionToBool - Determines whether this conversion is
215/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000216/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000217/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000218bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000219 // Note that FromType has not necessarily been transformed by the
220 // array-to-pointer or function-to-pointer implicit conversions, so
221 // check for their presence as well as checking whether FromType is
222 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000223 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000224 (getFromType()->isPointerType() ||
225 getFromType()->isObjCObjectPointerType() ||
226 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000227 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
229 return true;
230
231 return false;
232}
233
Douglas Gregor5c407d92008-10-23 00:40:37 +0000234/// isPointerConversionToVoidPointer - Determines whether this
235/// conversion is a conversion of a pointer to a void pointer. This is
236/// used as part of the ranking of standard conversion sequences (C++
237/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000238bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000239StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000240isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000241 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000242 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000243
244 // Note that FromType has not necessarily been transformed by the
245 // array-to-pointer implicit conversion, so check for its presence
246 // and redo the conversion to get a pointer.
247 if (First == ICK_Array_To_Pointer)
248 FromType = Context.getArrayDecayedType(FromType);
249
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000250 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000251 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000252 return ToPtrType->getPointeeType()->isVoidType();
253
254 return false;
255}
256
Richard Smith66e05fe2012-01-18 05:21:49 +0000257/// Skip any implicit casts which could be either part of a narrowing conversion
258/// or after one in an implicit conversion.
259static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
260 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
261 switch (ICE->getCastKind()) {
262 case CK_NoOp:
263 case CK_IntegralCast:
264 case CK_IntegralToBoolean:
265 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000266 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000267 case CK_FloatingToIntegral:
268 case CK_FloatingToBoolean:
269 case CK_FloatingCast:
270 Converted = ICE->getSubExpr();
271 continue;
272
273 default:
274 return Converted;
275 }
276 }
277
278 return Converted;
279}
280
281/// Check if this standard conversion sequence represents a narrowing
282/// conversion, according to C++11 [dcl.init.list]p7.
283///
284/// \param Ctx The AST context.
285/// \param Converted The result of applying this standard conversion sequence.
286/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
287/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000288/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
289/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000290NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000291StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
292 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000293 APValue &ConstantValue,
294 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000295 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000296
297 // C++11 [dcl.init.list]p7:
298 // A narrowing conversion is an implicit conversion ...
299 QualType FromType = getToType(0);
300 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000301
302 // A conversion to an enumeration type is narrowing if the conversion to
303 // the underlying type is narrowing. This only arises for expressions of
304 // the form 'Enum{init}'.
305 if (auto *ET = ToType->getAs<EnumType>())
306 ToType = ET->getDecl()->getIntegerType();
307
Richard Smith66e05fe2012-01-18 05:21:49 +0000308 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000309 // 'bool' is an integral type; dispatch to the right place to handle it.
310 case ICK_Boolean_Conversion:
311 if (FromType->isRealFloatingType())
312 goto FloatingIntegralConversion;
313 if (FromType->isIntegralOrUnscopedEnumerationType())
314 goto IntegralConversion;
315 // Boolean conversions can be from pointers and pointers to members
316 // [conv.bool], and those aren't considered narrowing conversions.
317 return NK_Not_Narrowing;
318
Richard Smith66e05fe2012-01-18 05:21:49 +0000319 // -- from a floating-point type to an integer type, or
320 //
321 // -- from an integer type or unscoped enumeration type to a floating-point
322 // type, except where the source is a constant expression and the actual
323 // value after conversion will fit into the target type and will produce
324 // the original value when converted back to the original type, or
325 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000326 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
328 return NK_Type_Narrowing;
329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
330 llvm::APSInt IntConstantValue;
331 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000332
333 // If it's value-dependent, we can't tell whether it's narrowing.
334 if (Initializer->isValueDependent())
335 return NK_Dependent_Narrowing;
336
Richard Smith66e05fe2012-01-18 05:21:49 +0000337 if (Initializer &&
338 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
339 // Convert the integer to the floating type.
340 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
341 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
342 llvm::APFloat::rmNearestTiesToEven);
343 // And back.
344 llvm::APSInt ConvertedValue = IntConstantValue;
345 bool ignored;
346 Result.convertToInteger(ConvertedValue,
347 llvm::APFloat::rmTowardZero, &ignored);
348 // If the resulting value is different, this was a narrowing conversion.
349 if (IntConstantValue != ConvertedValue) {
350 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000351 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000352 return NK_Constant_Narrowing;
353 }
354 } else {
355 // Variables are always narrowings.
356 return NK_Variable_Narrowing;
357 }
358 }
359 return NK_Not_Narrowing;
360
361 // -- from long double to double or float, or from double to float, except
362 // where the source is a constant expression and the actual value after
363 // conversion is within the range of values that can be represented (even
364 // if it cannot be represented exactly), or
365 case ICK_Floating_Conversion:
366 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
367 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
368 // FromType is larger than ToType.
369 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000370
371 // If it's value-dependent, we can't tell whether it's narrowing.
372 if (Initializer->isValueDependent())
373 return NK_Dependent_Narrowing;
374
Richard Smith66e05fe2012-01-18 05:21:49 +0000375 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
376 // Constant!
377 assert(ConstantValue.isFloat());
378 llvm::APFloat FloatVal = ConstantValue.getFloat();
379 // Convert the source value into the target type.
380 bool ignored;
381 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
382 Ctx.getFloatTypeSemantics(ToType),
383 llvm::APFloat::rmNearestTiesToEven, &ignored);
384 // If there was no overflow, the source value is within the range of
385 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000386 if (ConvertStatus & llvm::APFloat::opOverflow) {
387 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000388 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000389 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000390 } else {
391 return NK_Variable_Narrowing;
392 }
393 }
394 return NK_Not_Narrowing;
395
396 // -- from an integer type or unscoped enumeration type to an integer type
397 // that cannot represent all the values of the original type, except where
398 // the source is a constant expression and the actual value after
399 // conversion will fit into the target type and will produce the original
400 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000401 case ICK_Integral_Conversion:
402 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000403 assert(FromType->isIntegralOrUnscopedEnumerationType());
404 assert(ToType->isIntegralOrUnscopedEnumerationType());
405 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
406 const unsigned FromWidth = Ctx.getIntWidth(FromType);
407 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
408 const unsigned ToWidth = Ctx.getIntWidth(ToType);
409
410 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000411 (FromWidth == ToWidth && FromSigned != ToSigned) ||
412 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000413 // Not all values of FromType can be represented in ToType.
414 llvm::APSInt InitializerValue;
415 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000416
417 // If it's value-dependent, we can't tell whether it's narrowing.
418 if (Initializer->isValueDependent())
419 return NK_Dependent_Narrowing;
420
Richard Smith25a80d42012-06-13 01:07:41 +0000421 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
422 // Such conversions on variables are always narrowing.
423 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000424 }
425 bool Narrowing = false;
426 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000427 // Negative -> unsigned is narrowing. Otherwise, more bits is never
428 // narrowing.
429 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000430 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000431 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000432 // Add a bit to the InitializerValue so we don't have to worry about
433 // signed vs. unsigned comparisons.
434 InitializerValue = InitializerValue.extend(
435 InitializerValue.getBitWidth() + 1);
436 // Convert the initializer to and from the target width and signed-ness.
437 llvm::APSInt ConvertedValue = InitializerValue;
438 ConvertedValue = ConvertedValue.trunc(ToWidth);
439 ConvertedValue.setIsSigned(ToSigned);
440 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
441 ConvertedValue.setIsSigned(InitializerValue.isSigned());
442 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000443 if (ConvertedValue != InitializerValue)
444 Narrowing = true;
445 }
446 if (Narrowing) {
447 ConstantType = Initializer->getType();
448 ConstantValue = APValue(InitializerValue);
449 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000450 }
451 }
452 return NK_Not_Narrowing;
453 }
454
455 default:
456 // Other kinds of conversions are not narrowings.
457 return NK_Not_Narrowing;
458 }
459}
460
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000461/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000462/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000463LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000464 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000465 bool PrintedSomething = false;
466 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000467 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000468 PrintedSomething = true;
469 }
470
471 if (Second != ICK_Identity) {
472 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000473 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000475 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000476
477 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000478 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000479 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000480 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000481 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000482 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000483 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 PrintedSomething = true;
485 }
486
487 if (Third != ICK_Identity) {
488 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000489 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000491 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000492 PrintedSomething = true;
493 }
494
495 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000496 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 }
498}
499
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000500/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000502void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000503 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000505 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000506 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000508 if (ConversionFunction)
509 OS << '\'' << *ConversionFunction << '\'';
510 else
511 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000513 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000514 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000515 }
516}
517
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000518/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000519/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000520void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000521 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000522 if (isStdInitializerListElement())
523 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524 switch (ConversionKind) {
525 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000526 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000527 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528 break;
529 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000530 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000531 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000532 break;
533 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000534 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000535 break;
John McCall0d1da222010-01-12 00:44:57 +0000536 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000537 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000538 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000539 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000540 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000541 break;
542 }
543
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000544 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000545}
546
John McCall0d1da222010-01-12 00:44:57 +0000547void AmbiguousConversionSequence::construct() {
548 new (&conversions()) ConversionSet();
549}
550
551void AmbiguousConversionSequence::destruct() {
552 conversions().~ConversionSet();
553}
554
555void
556AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
557 FromTypePtr = O.FromTypePtr;
558 ToTypePtr = O.ToTypePtr;
559 new (&conversions()) ConversionSet(O.conversions());
560}
561
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000562namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000563 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000564 // template argument information.
565 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000566 TemplateArgument FirstArg;
567 TemplateArgument SecondArg;
568 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000569 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000570 // template parameter and template argument information.
571 struct DFIParamWithArguments : DFIArguments {
572 TemplateParameter Param;
573 };
Richard Smith9b534542015-12-31 02:02:54 +0000574 // Structure used by DeductionFailureInfo to store template argument
575 // information and the index of the problematic call argument.
576 struct DFIDeducedMismatchArgs : DFIArguments {
577 TemplateArgumentList *TemplateArgs;
578 unsigned CallArgIndex;
579 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000580}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000582/// \brief Convert from Sema's representation of template deduction information
583/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000584DeductionFailureInfo
585clang::MakeDeductionFailureInfo(ASTContext &Context,
586 Sema::TemplateDeductionResult TDK,
587 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000588 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000589 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000590 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000591 switch (TDK) {
Renato Golindad96d62017-01-02 11:15:42 +0000592 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000593 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000595 case Sema::TDK_TooManyArguments:
596 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000597 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000598 case Sema::TDK_CUDATargetMismatch:
Richard Smith9b534542015-12-31 02:02:54 +0000599 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000603 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000604 Result.Data = Info.Param.getOpaqueValue();
605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Richard Smithc92d2062017-01-05 23:02:44 +0000607 case Sema::TDK_DeducedMismatch:
608 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +0000609 // FIXME: Should allocate from normal heap so that we can free this later.
610 auto *Saved = new (Context) DFIDeducedMismatchArgs;
611 Saved->FirstArg = Info.FirstArg;
612 Saved->SecondArg = Info.SecondArg;
613 Saved->TemplateArgs = Info.take();
614 Saved->CallArgIndex = Info.CallArgIndex;
615 Result.Data = Saved;
616 break;
617 }
618
Richard Smith44ecdbd2013-01-31 05:19:49 +0000619 case Sema::TDK_NonDeducedMismatch: {
620 // FIXME: Should allocate from normal heap so that we can free this later.
621 DFIArguments *Saved = new (Context) DFIArguments;
622 Saved->FirstArg = Info.FirstArg;
623 Saved->SecondArg = Info.SecondArg;
624 Result.Data = Saved;
625 break;
626 }
627
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000629 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000630 // FIXME: Should allocate from normal heap so that we can free this later.
631 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 Saved->Param = Info.Param;
633 Saved->FirstArg = Info.FirstArg;
634 Saved->SecondArg = Info.SecondArg;
635 Result.Data = Saved;
636 break;
637 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000639 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000640 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000641 if (Info.hasSFINAEDiagnostic()) {
642 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643 SourceLocation(), PartialDiagnostic::NullDiagnostic());
644 Info.takeSFINAEDiagnostic(*Diag);
645 Result.HasDiagnostic = true;
646 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000647 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000648 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000649
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000650 return Result;
651}
John McCall0d1da222010-01-12 00:44:57 +0000652
Larisse Voufo98b20f12013-07-19 23:00:19 +0000653void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000654 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
655 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000656 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000657 case Sema::TDK_InstantiationDepth:
658 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000659 case Sema::TDK_TooManyArguments:
660 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000661 case Sema::TDK_InvalidExplicitArguments:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000662 case Sema::TDK_CUDATargetMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000663 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000665 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000666 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000667 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000668 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000669 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000670 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000671 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000672 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000673
674 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000675 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000676 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000677 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
678 Diag->~PartialDiagnosticAt();
679 HasDiagnostic = false;
680 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000681 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682
Douglas Gregor461761d2010-05-08 18:20:53 +0000683 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000684 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000685 break;
686 }
687}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Larisse Voufo98b20f12013-07-19 23:00:19 +0000689PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000690 if (HasDiagnostic)
691 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000692 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000693}
694
Larisse Voufo98b20f12013-07-19 23:00:19 +0000695TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000696 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
697 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000698 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000699 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000700 case Sema::TDK_TooManyArguments:
701 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000702 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000703 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000704 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000705 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000706 case Sema::TDK_CUDATargetMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000707 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000708
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000709 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000710 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000711 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000712
713 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000714 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000715 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000717 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000718 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000719 break;
720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000722 return TemplateParameter();
723}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724
Larisse Voufo98b20f12013-07-19 23:00:19 +0000725TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000727 case Sema::TDK_Success:
728 case Sema::TDK_Invalid:
729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_TooManyArguments:
731 case Sema::TDK_TooFewArguments:
732 case Sema::TDK_Incomplete:
733 case Sema::TDK_InvalidExplicitArguments:
734 case Sema::TDK_Inconsistent:
735 case Sema::TDK_Underqualified:
736 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000737 case Sema::TDK_CUDATargetMismatch:
Craig Topperc3ec1492014-05-26 06:22:03 +0000738 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000739
Richard Smith9b534542015-12-31 02:02:54 +0000740 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000741 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000742 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
743
Richard Smith44ecdbd2013-01-31 05:19:49 +0000744 case Sema::TDK_SubstitutionFailure:
745 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000746
Richard Smith44ecdbd2013-01-31 05:19:49 +0000747 // Unhandled
748 case Sema::TDK_MiscellaneousDeductionFailure:
749 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000750 }
751
Craig Topperc3ec1492014-05-26 06:22:03 +0000752 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000753}
754
Larisse Voufo98b20f12013-07-19 23:00:19 +0000755const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000756 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
757 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000758 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000759 case Sema::TDK_InstantiationDepth:
760 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000761 case Sema::TDK_TooManyArguments:
762 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000763 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000764 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000765 case Sema::TDK_CUDATargetMismatch:
Craig Topperc3ec1492014-05-26 06:22:03 +0000766 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000767
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000768 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000769 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000770 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000771 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000772 case Sema::TDK_NonDeducedMismatch:
773 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000774
Douglas Gregor461761d2010-05-08 18:20:53 +0000775 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000776 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000777 break;
778 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000779
Craig Topperc3ec1492014-05-26 06:22:03 +0000780 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000781}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000782
Larisse Voufo98b20f12013-07-19 23:00:19 +0000783const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000784 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
785 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000786 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000787 case Sema::TDK_InstantiationDepth:
788 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000789 case Sema::TDK_TooManyArguments:
790 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000791 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000792 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000793 case Sema::TDK_CUDATargetMismatch:
Craig Topperc3ec1492014-05-26 06:22:03 +0000794 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000795
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000796 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000797 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000798 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000799 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000800 case Sema::TDK_NonDeducedMismatch:
801 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000802
Douglas Gregor461761d2010-05-08 18:20:53 +0000803 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000804 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000805 break;
806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000807
Craig Topperc3ec1492014-05-26 06:22:03 +0000808 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000809}
810
Richard Smith9b534542015-12-31 02:02:54 +0000811llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
Richard Smithc92d2062017-01-05 23:02:44 +0000812 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
813 case Sema::TDK_DeducedMismatch:
814 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000815 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
816
Richard Smithc92d2062017-01-05 23:02:44 +0000817 default:
818 return llvm::None;
819 }
Richard Smith9b534542015-12-31 02:02:54 +0000820}
821
Benjamin Kramer97e59492012-10-09 15:52:25 +0000822void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000823 for (iterator i = begin(), e = end(); i != e; ++i) {
Renato Golindad96d62017-01-02 11:15:42 +0000824 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
825 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000826 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
827 i->DeductionFailure.Destroy();
828 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000829}
830
831void OverloadCandidateSet::clear() {
832 destroyCandidates();
George Burgess IVbc7f44c2016-12-02 21:00:12 +0000833 ConversionSequenceAllocator.Reset();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000834 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000835 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000836 Functions.clear();
837}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000838
John McCall4124c492011-10-17 18:40:02 +0000839namespace {
840 class UnbridgedCastsSet {
841 struct Entry {
842 Expr **Addr;
843 Expr *Saved;
844 };
845 SmallVector<Entry, 2> Entries;
846
847 public:
848 void save(Sema &S, Expr *&E) {
849 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
850 Entry entry = { &E, E };
851 Entries.push_back(entry);
852 E = S.stripARCUnbridgedCast(E);
853 }
854
855 void restore() {
856 for (SmallVectorImpl<Entry>::iterator
857 i = Entries.begin(), e = Entries.end(); i != e; ++i)
858 *i->Addr = i->Saved;
859 }
860 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000861}
John McCall4124c492011-10-17 18:40:02 +0000862
863/// checkPlaceholderForOverload - Do any interesting placeholder-like
864/// preprocessing on the given expression.
865///
866/// \param unbridgedCasts a collection to which to add unbridged casts;
867/// without this, they will be immediately diagnosed as errors
868///
869/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000870static bool
871checkPlaceholderForOverload(Sema &S, Expr *&E,
872 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000873 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
874 // We can't handle overloaded expressions here because overload
875 // resolution might reasonably tweak them.
876 if (placeholder->getKind() == BuiltinType::Overload) return false;
877
878 // If the context potentially accepts unbridged ARC casts, strip
879 // the unbridged cast and add it to the collection for later restoration.
880 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
881 unbridgedCasts) {
882 unbridgedCasts->save(S, E);
883 return false;
884 }
885
886 // Go ahead and check everything else.
887 ExprResult result = S.CheckPlaceholderExpr(E);
888 if (result.isInvalid())
889 return true;
890
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000891 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000892 return false;
893 }
894
895 // Nothing to do.
896 return false;
897}
898
899/// checkArgPlaceholdersForOverload - Check a set of call operands for
900/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000901static bool checkArgPlaceholdersForOverload(Sema &S,
902 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000903 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000904 for (unsigned i = 0, e = Args.size(); i != e; ++i)
905 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000906 return true;
907
908 return false;
909}
910
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000911// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000912// overload of the declarations in Old. This routine returns false if
913// New and Old cannot be overloaded, e.g., if New has the same
914// signature as some function in Old (C++ 1.3.10) or if the Old
915// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000916// it does return false, MatchedDecl will point to the decl that New
917// cannot be overloaded with. This decl may be a UsingShadowDecl on
918// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000919//
920// Example: Given the following input:
921//
922// void f(int, float); // #1
923// void f(int, int); // #2
924// int f(int, int); // #3
925//
926// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000927// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000928//
John McCall3d988d92009-12-02 08:47:38 +0000929// When we process #2, Old contains only the FunctionDecl for #1. By
930// comparing the parameter types, we see that #1 and #2 are overloaded
931// (since they have different signatures), so this routine returns
932// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000933//
John McCall3d988d92009-12-02 08:47:38 +0000934// When we process #3, Old is an overload set containing #1 and #2. We
935// compare the signatures of #3 to #1 (they're overloaded, so we do
936// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
937// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000938// signature), IsOverload returns false and MatchedDecl will be set to
939// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000940//
941// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
942// into a class by a using declaration. The rules for whether to hide
943// shadow declarations ignore some properties which otherwise figure
944// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000945Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000946Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
947 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000948 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000949 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000950 NamedDecl *OldD = *I;
951
952 bool OldIsUsingDecl = false;
953 if (isa<UsingShadowDecl>(OldD)) {
954 OldIsUsingDecl = true;
955
956 // We can always introduce two using declarations into the same
957 // context, even if they have identical signatures.
958 if (NewIsUsingDecl) continue;
959
960 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
961 }
962
Richard Smithf091e122015-09-15 01:28:55 +0000963 // A using-declaration does not conflict with another declaration
964 // if one of them is hidden.
965 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
966 continue;
967
John McCalle9cccd82010-06-16 08:42:20 +0000968 // If either declaration was introduced by a using declaration,
969 // we'll need to use slightly different rules for matching.
970 // Essentially, these rules are the normal rules, except that
971 // function templates hide function templates with different
972 // return types or template parameter lists.
973 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000974 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
975 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000976
Alp Tokera2794f92014-01-22 07:29:52 +0000977 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000978 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
979 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
980 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
981 continue;
982 }
983
Alp Tokera2794f92014-01-22 07:29:52 +0000984 if (!isa<FunctionTemplateDecl>(OldD) &&
985 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000986 continue;
987
John McCalldaa3d6b2009-12-09 03:35:25 +0000988 Match = *I;
989 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000990 }
Richard Smith151c4562016-12-20 21:35:28 +0000991 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000992 // We can overload with these, which can show up when doing
993 // redeclaration checks for UsingDecls.
994 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000995 } else if (isa<TagDecl>(OldD)) {
996 // We can always overload with tags by hiding them.
Richard Smithd8a9e372016-12-18 21:39:37 +0000997 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000998 // Optimistically assume that an unresolved using decl will
999 // overload; if it doesn't, we'll have to diagnose during
1000 // template instantiation.
Richard Smithd8a9e372016-12-18 21:39:37 +00001001 //
1002 // Exception: if the scope is dependent and this is not a class
1003 // member, the using declaration can only introduce an enumerator.
1004 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1005 Match = *I;
1006 return Ovl_NonFunction;
1007 }
John McCall84d87672009-12-10 09:41:52 +00001008 } else {
John McCall1f82f242009-11-18 22:49:29 +00001009 // (C++ 13p1):
1010 // Only function declarations can be overloaded; object and type
1011 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +00001012 Match = *I;
1013 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +00001014 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001015 }
John McCall1f82f242009-11-18 22:49:29 +00001016
John McCalldaa3d6b2009-12-09 03:35:25 +00001017 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +00001018}
1019
Richard Smithac974a32013-06-30 09:48:50 +00001020bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001021 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001022 // C++ [basic.start.main]p2: This function shall not be overloaded.
1023 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001024 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001025
David Majnemerc729b0b2013-09-16 22:44:20 +00001026 // MSVCRT user defined entry points cannot be overloaded.
1027 if (New->isMSVCRTEntryPoint())
1028 return false;
1029
John McCall1f82f242009-11-18 22:49:29 +00001030 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1031 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1032
1033 // C++ [temp.fct]p2:
1034 // A function template can be overloaded with other function templates
1035 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001036 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001037 return true;
1038
1039 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001040 QualType OldQType = Context.getCanonicalType(Old->getType());
1041 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001042
1043 // Compare the signatures (C++ 1.3.10) of the two functions to
1044 // determine whether they are overloads. If we find any mismatch
1045 // in the signature, they are overloads.
1046
1047 // If either of these functions is a K&R-style function (no
1048 // prototype), then we consider them to have matching signatures.
1049 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1050 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1051 return false;
1052
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001053 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1054 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001055
1056 // The signature of a function includes the types of its
1057 // parameters (C++ 1.3.10), which includes the presence or absence
1058 // of the ellipsis; see C++ DR 357).
1059 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001060 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001061 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001062 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001063 return true;
1064
1065 // C++ [temp.over.link]p4:
1066 // The signature of a function template consists of its function
1067 // signature, its return type and its template parameter list. The names
1068 // of the template parameters are significant only for establishing the
1069 // relationship between the template parameters and the rest of the
1070 // signature.
1071 //
1072 // We check the return type and template parameter lists for function
1073 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001074 //
1075 // However, we don't consider either of these when deciding whether
1076 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001077 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001078 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1079 OldTemplate->getTemplateParameters(),
1080 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001081 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001082 return true;
1083
1084 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001085 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001086 //
1087 // As part of this, also check whether one of the member functions
1088 // is static, in which case they are not overloads (C++
1089 // 13.1p2). While not part of the definition of the signature,
1090 // this check is important to determine whether these functions
1091 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001092 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1093 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001094 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001095 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1096 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001097 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001098 (OldMethod->getRefQualifier() == RQ_None ||
1099 NewMethod->getRefQualifier() == RQ_None)) {
1100 // C++0x [over.load]p2:
1101 // - Member function declarations with the same name and the same
1102 // parameter-type-list as well as member function template
1103 // declarations with the same name, the same parameter-type-list, and
1104 // the same template parameter lists cannot be overloaded if any of
1105 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001106 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001107 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001108 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001109 }
1110 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001112
Richard Smith574f4f62013-01-14 05:37:29 +00001113 // We may not have applied the implicit const for a constexpr member
1114 // function yet (because we haven't yet resolved whether this is a static
1115 // or non-static member function). Add it now, on the assumption that this
1116 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001117 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001118 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001119 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001120 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001121 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001122
1123 // We do not allow overloading based off of '__restrict'.
1124 OldQuals &= ~Qualifiers::Restrict;
1125 NewQuals &= ~Qualifiers::Restrict;
1126 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001127 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001129
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001130 // Though pass_object_size is placed on parameters and takes an argument, we
1131 // consider it to be a function-level modifier for the sake of function
1132 // identity. Either the function has one or more parameters with
1133 // pass_object_size or it doesn't.
1134 if (functionHasPassObjectSizeParams(New) !=
1135 functionHasPassObjectSizeParams(Old))
1136 return true;
1137
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001138 // enable_if attributes are an order-sensitive part of the signature.
1139 for (specific_attr_iterator<EnableIfAttr>
1140 NewI = New->specific_attr_begin<EnableIfAttr>(),
1141 NewE = New->specific_attr_end<EnableIfAttr>(),
1142 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1143 OldE = Old->specific_attr_end<EnableIfAttr>();
1144 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1145 if (NewI == NewE || OldI == OldE)
1146 return true;
1147 llvm::FoldingSetNodeID NewID, OldID;
1148 NewI->getCond()->Profile(NewID, Context, true);
1149 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001150 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001151 return true;
1152 }
1153
Justin Lebarba122ab2016-03-30 23:30:21 +00001154 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001155 // Don't allow overloading of destructors. (In theory we could, but it
1156 // would be a giant change to clang.)
1157 if (isa<CXXDestructorDecl>(New))
1158 return false;
1159
Artem Belevich94a55e82015-09-22 17:22:59 +00001160 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1161 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001162 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001163 return false;
1164
1165 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1166
Justin Lebar53b000af2016-10-03 16:48:27 +00001167 // Allow overloading of functions with same signature and different CUDA
1168 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001169 return NewTarget != OldTarget;
1170 }
1171
John McCall1f82f242009-11-18 22:49:29 +00001172 // The signatures match; this is not an overload.
1173 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001174}
1175
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001176/// \brief Checks availability of the function depending on the current
1177/// function context. Inside an unavailable function, unavailability is ignored.
1178///
1179/// \returns true if \arg FD is unavailable and current context is inside
1180/// an available function, false otherwise.
1181bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001182 if (!FD->isUnavailable())
1183 return false;
1184
1185 // Walk up the context of the caller.
1186 Decl *C = cast<Decl>(CurContext);
1187 do {
1188 if (C->isUnavailable())
1189 return false;
1190 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1191 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001192}
1193
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001194/// \brief Tries a user-defined conversion from From to ToType.
1195///
1196/// Produces an implicit conversion sequence for when a standard conversion
1197/// is not an option. See TryImplicitConversion for more information.
1198static ImplicitConversionSequence
1199TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1200 bool SuppressUserConversions,
1201 bool AllowExplicit,
1202 bool InOverloadResolution,
1203 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001204 bool AllowObjCWritebackConversion,
1205 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001206 ImplicitConversionSequence ICS;
1207
1208 if (SuppressUserConversions) {
1209 // We're not in the case above, so there is no conversion that
1210 // we can perform.
1211 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1212 return ICS;
1213 }
1214
1215 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001216 OverloadCandidateSet Conversions(From->getExprLoc(),
1217 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001218 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1219 Conversions, AllowExplicit,
1220 AllowObjCConversionOnExplicit)) {
1221 case OR_Success:
1222 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001223 ICS.setUserDefined();
1224 // C++ [over.ics.user]p4:
1225 // A conversion of an expression of class type to the same class
1226 // type is given Exact Match rank, and a conversion of an
1227 // expression of class type to a base class of that type is
1228 // given Conversion rank, in spite of the fact that a copy
1229 // constructor (i.e., a user-defined conversion function) is
1230 // called for those cases.
1231 if (CXXConstructorDecl *Constructor
1232 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1233 QualType FromCanon
1234 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1235 QualType ToCanon
1236 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1237 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001238 (FromCanon == ToCanon ||
1239 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001240 // Turn this into a "standard" conversion sequence, so that it
1241 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001242 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001243 ICS.setStandard();
1244 ICS.Standard.setAsIdentityConversion();
1245 ICS.Standard.setFromType(From->getType());
1246 ICS.Standard.setAllToTypes(ToType);
1247 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001248 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001249 if (ToCanon != FromCanon)
1250 ICS.Standard.Second = ICK_Derived_To_Base;
1251 }
1252 }
Richard Smith48372b62015-01-27 03:30:40 +00001253 break;
1254
1255 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001256 ICS.setAmbiguous();
1257 ICS.Ambiguous.setFromType(From->getType());
1258 ICS.Ambiguous.setToType(ToType);
1259 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1260 Cand != Conversions.end(); ++Cand)
1261 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001262 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001263 break;
Richard Smith48372b62015-01-27 03:30:40 +00001264
1265 // Fall through.
1266 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001267 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001268 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001269 }
1270
1271 return ICS;
1272}
1273
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001274/// TryImplicitConversion - Attempt to perform an implicit conversion
1275/// from the given expression (Expr) to the given type (ToType). This
1276/// function returns an implicit conversion sequence that can be used
1277/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001278///
1279/// void f(float f);
1280/// void g(int i) { f(i); }
1281///
1282/// this routine would produce an implicit conversion sequence to
1283/// describe the initialization of f from i, which will be a standard
1284/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1285/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1286//
1287/// Note that this routine only determines how the conversion can be
1288/// performed; it does not actually perform the conversion. As such,
1289/// it will not produce any diagnostics if no conversion is available,
1290/// but will instead return an implicit conversion sequence of kind
1291/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001292///
1293/// If @p SuppressUserConversions, then user-defined conversions are
1294/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001295/// If @p AllowExplicit, then explicit user-defined conversions are
1296/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001297///
1298/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1299/// writeback conversion, which allows __autoreleasing id* parameters to
1300/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001301static ImplicitConversionSequence
1302TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1303 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001305 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001306 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001307 bool AllowObjCWritebackConversion,
1308 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001309 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001310 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001311 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001312 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001313 return ICS;
1314 }
1315
David Blaikiebbafb8a2012-03-11 07:00:24 +00001316 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001317 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001318 return ICS;
1319 }
1320
Douglas Gregor836a7e82010-08-11 02:15:33 +00001321 // C++ [over.ics.user]p4:
1322 // A conversion of an expression of class type to the same class
1323 // type is given Exact Match rank, and a conversion of an
1324 // expression of class type to a base class of that type is
1325 // given Conversion rank, in spite of the fact that a copy/move
1326 // constructor (i.e., a user-defined conversion function) is
1327 // called for those cases.
1328 QualType FromType = From->getType();
1329 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001330 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001331 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001332 ICS.setStandard();
1333 ICS.Standard.setAsIdentityConversion();
1334 ICS.Standard.setFromType(FromType);
1335 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001336
Douglas Gregor5ab11652010-04-17 22:01:05 +00001337 // We don't actually check at this point whether there is a valid
1338 // copy/move constructor, since overloading just assumes that it
1339 // exists. When we actually perform initialization, we'll find the
1340 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001341 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001342
Douglas Gregor5ab11652010-04-17 22:01:05 +00001343 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001344 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001345 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001346
Douglas Gregor836a7e82010-08-11 02:15:33 +00001347 return ICS;
1348 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001349
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001350 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1351 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001352 AllowObjCWritebackConversion,
1353 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001354}
1355
John McCall31168b02011-06-15 23:02:42 +00001356ImplicitConversionSequence
1357Sema::TryImplicitConversion(Expr *From, QualType ToType,
1358 bool SuppressUserConversions,
1359 bool AllowExplicit,
1360 bool InOverloadResolution,
1361 bool CStyle,
1362 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001363 return ::TryImplicitConversion(*this, From, ToType,
1364 SuppressUserConversions, AllowExplicit,
1365 InOverloadResolution, CStyle,
1366 AllowObjCWritebackConversion,
1367 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001368}
1369
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001370/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001371/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001372/// converted expression. Flavor is the kind of conversion we're
1373/// performing, used in the error message. If @p AllowExplicit,
1374/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001375ExprResult
1376Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001377 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001378 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001379 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001380}
1381
John Wiegley01296292011-04-08 18:41:53 +00001382ExprResult
1383Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001384 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001385 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001386 if (checkPlaceholderForOverload(*this, From))
1387 return ExprError();
1388
John McCall31168b02011-06-15 23:02:42 +00001389 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1390 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001391 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001392 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001393 if (getLangOpts().ObjC1)
1394 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1395 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001396 ICS = ::TryImplicitConversion(*this, From, ToType,
1397 /*SuppressUserConversions=*/false,
1398 AllowExplicit,
1399 /*InOverloadResolution=*/false,
1400 /*CStyle=*/false,
1401 AllowObjCWritebackConversion,
1402 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001403 return PerformImplicitConversion(From, ToType, ICS, Action);
1404}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001405
1406/// \brief Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001407/// conversion that strips "noexcept" or "noreturn" off the nested function
1408/// type.
1409bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001410 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001411 if (Context.hasSameUnqualifiedType(FromType, ToType))
1412 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001413
John McCall991eb4b2010-12-21 00:44:39 +00001414 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001415 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001416 // where F adds one of the following at most once:
1417 // - a pointer
1418 // - a member pointer
1419 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001420 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001421 CanQualType CanTo = Context.getCanonicalType(ToType);
1422 CanQualType CanFrom = Context.getCanonicalType(FromType);
1423 Type::TypeClass TyClass = CanTo->getTypeClass();
1424 if (TyClass != CanFrom->getTypeClass()) return false;
1425 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1426 if (TyClass == Type::Pointer) {
1427 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1428 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1429 } else if (TyClass == Type::BlockPointer) {
1430 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1431 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1432 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001433 auto ToMPT = CanTo.getAs<MemberPointerType>();
1434 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1435 // A function pointer conversion cannot change the class of the function.
1436 if (ToMPT->getClass() != FromMPT->getClass())
1437 return false;
1438 CanTo = ToMPT->getPointeeType();
1439 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001440 } else {
1441 return false;
1442 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001443
John McCall991eb4b2010-12-21 00:44:39 +00001444 TyClass = CanTo->getTypeClass();
1445 if (TyClass != CanFrom->getTypeClass()) return false;
1446 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1447 return false;
1448 }
1449
Richard Smith3c4f8d22016-10-16 17:54:23 +00001450 const auto *FromFn = cast<FunctionType>(CanFrom);
1451 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001452
Richard Smith6f427402016-10-20 00:01:36 +00001453 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001454 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1455
1456 bool Changed = false;
1457
1458 // Drop 'noreturn' if not present in target type.
1459 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1460 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1461 Changed = true;
1462 }
1463
1464 // Drop 'noexcept' if not present in target type.
1465 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001466 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001467 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1468 FromFn = cast<FunctionType>(
1469 Context.getFunctionType(FromFPT->getReturnType(),
1470 FromFPT->getParamTypes(),
1471 FromFPT->getExtProtoInfo().withExceptionSpec(
1472 FunctionProtoType::ExceptionSpecInfo()))
1473 .getTypePtr());
1474 Changed = true;
1475 }
1476 }
1477
1478 if (!Changed)
1479 return false;
1480
John McCall991eb4b2010-12-21 00:44:39 +00001481 assert(QualType(FromFn, 0).isCanonical());
1482 if (QualType(FromFn, 0) != CanTo) return false;
1483
1484 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001485 return true;
1486}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001487
Douglas Gregor46188682010-05-18 22:42:18 +00001488/// \brief Determine whether the conversion from FromType to ToType is a valid
1489/// vector conversion.
1490///
1491/// \param ICK Will be set to the vector conversion kind, if this is a vector
1492/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001493static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001494 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001495 // We need at least one of these types to be a vector type to have a vector
1496 // conversion.
1497 if (!ToType->isVectorType() && !FromType->isVectorType())
1498 return false;
1499
1500 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001501 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001502 return false;
1503
1504 // There are no conversions between extended vector types, only identity.
1505 if (ToType->isExtVectorType()) {
1506 // There are no conversions between extended vector types other than the
1507 // identity conversion.
1508 if (FromType->isExtVectorType())
1509 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001510
Douglas Gregor46188682010-05-18 22:42:18 +00001511 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001512 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001513 ICK = ICK_Vector_Splat;
1514 return true;
1515 }
1516 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001517
1518 // We can perform the conversion between vector types in the following cases:
1519 // 1)vector types are equivalent AltiVec and GCC vector types
1520 // 2)lax vector conversions are permitted and the vector types are of the
1521 // same size
1522 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001523 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1524 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001525 ICK = ICK_Vector_Conversion;
1526 return true;
1527 }
Douglas Gregor46188682010-05-18 22:42:18 +00001528 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001529
Douglas Gregor46188682010-05-18 22:42:18 +00001530 return false;
1531}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001532
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001533static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1534 bool InOverloadResolution,
1535 StandardConversionSequence &SCS,
1536 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001537
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001538/// IsStandardConversion - Determines whether there is a standard
1539/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1540/// expression From to the type ToType. Standard conversion sequences
1541/// only consider non-class types; for conversions that involve class
1542/// types, use TryImplicitConversion. If a conversion exists, SCS will
1543/// contain the standard conversion sequence required to perform this
1544/// conversion and this routine will return true. Otherwise, this
1545/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001546static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1547 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001548 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001549 bool CStyle,
1550 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001551 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001552
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001553 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001554 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001555 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001556 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001557 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001558
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001559 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001560 // abort early. When overloading in C, however, we do permit them.
1561 if (S.getLangOpts().CPlusPlus &&
1562 (FromType->isRecordType() || ToType->isRecordType()))
1563 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001564
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001565 // The first conversion can be an lvalue-to-rvalue conversion,
1566 // array-to-pointer conversion, or function-to-pointer conversion
1567 // (C++ 4p1).
1568
John McCall5c32be02010-08-24 20:38:10 +00001569 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001570 DeclAccessPair AccessPair;
1571 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001572 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001573 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001574 // We were able to resolve the address of the overloaded function,
1575 // so we can convert to the type of that function.
1576 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001577 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001578
1579 // we can sometimes resolve &foo<int> regardless of ToType, so check
1580 // if the type matches (identity) or we are converting to bool
1581 if (!S.Context.hasSameUnqualifiedType(
1582 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1583 QualType resultTy;
1584 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001585 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001586 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1587 // otherwise, only a boolean conversion is standard
1588 if (!ToType->isBooleanType())
1589 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001590 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001591
Chandler Carruthffce2452011-03-29 08:08:18 +00001592 // Check if the "from" expression is taking the address of an overloaded
1593 // function and recompute the FromType accordingly. Take advantage of the
1594 // fact that non-static member functions *must* have such an address-of
1595 // expression.
1596 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1597 if (Method && !Method->isStatic()) {
1598 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1599 "Non-unary operator on non-static member address");
1600 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1601 == UO_AddrOf &&
1602 "Non-address-of operator on non-static member address");
1603 const Type *ClassType
1604 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1605 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001606 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1607 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1608 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001609 "Non-address-of operator for overloaded function expression");
1610 FromType = S.Context.getPointerType(FromType);
1611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001612
Douglas Gregor980fb162010-04-29 18:24:40 +00001613 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001614 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1615 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001616 assert(S.Context.hasSameType(
1617 FromType,
1618 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001619 } else {
1620 return false;
1621 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001622 }
John McCall154a2fd2011-08-30 00:57:29 +00001623 // Lvalue-to-rvalue conversion (C++11 4.1):
1624 // A glvalue (3.10) of a non-function, non-array type T can
1625 // be converted to a prvalue.
1626 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001627 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001628 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001629 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001630 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001631
Douglas Gregorc79862f2012-04-12 17:51:55 +00001632 // C11 6.3.2.1p2:
1633 // ... if the lvalue has atomic type, the value has the non-atomic version
1634 // of the type of the lvalue ...
1635 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1636 FromType = Atomic->getValueType();
1637
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638 // If T is a non-class type, the type of the rvalue is the
1639 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001640 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1641 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001642 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001643 } else if (FromType->isArrayType()) {
1644 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001645 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001646
1647 // An lvalue or rvalue of type "array of N T" or "array of unknown
1648 // bound of T" can be converted to an rvalue of type "pointer to
1649 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001650 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001651
John McCall5c32be02010-08-24 20:38:10 +00001652 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001653 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001654 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001655
1656 // For the purpose of ranking in overload resolution
1657 // (13.3.3.1.1), this conversion is considered an
1658 // array-to-pointer conversion followed by a qualification
1659 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001660 SCS.Second = ICK_Identity;
1661 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001662 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001663 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001664 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001665 }
John McCall086a4642010-11-24 05:12:34 +00001666 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001667 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001668 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001669
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001670 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1671 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1672 if (!S.checkAddressOfFunctionIsAvailable(FD))
1673 return false;
1674
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675 // An lvalue of function type T can be converted to an rvalue of
1676 // type "pointer to T." The result is a pointer to the
1677 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001678 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001679 } else {
1680 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001681 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001682 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001683 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001684
1685 // The second conversion can be an integral promotion, floating
1686 // point promotion, integral conversion, floating point conversion,
1687 // floating-integral conversion, pointer conversion,
1688 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001689 // For overloading in C, this can also be a "compatible-type"
1690 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001691 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001692 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001693 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001694 // The unqualified versions of the types are the same: there's no
1695 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001696 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001697 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001698 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001699 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001700 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001701 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001702 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001703 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001704 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001705 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001706 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001707 SCS.Second = ICK_Complex_Promotion;
1708 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001709 } else if (ToType->isBooleanType() &&
1710 (FromType->isArithmeticType() ||
1711 FromType->isAnyPointerType() ||
1712 FromType->isBlockPointerType() ||
1713 FromType->isMemberPointerType() ||
1714 FromType->isNullPtrType())) {
1715 // Boolean conversions (C++ 4.12).
1716 SCS.Second = ICK_Boolean_Conversion;
1717 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001718 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001719 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001720 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001721 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001722 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001723 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001724 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001725 SCS.Second = ICK_Complex_Conversion;
1726 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001727 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1728 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001729 // Complex-real conversions (C99 6.3.1.7)
1730 SCS.Second = ICK_Complex_Real;
1731 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001732 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001733 // FIXME: disable conversions between long double and __float128 if
1734 // their representation is different until there is back end support
1735 // We of course allow this conversion if long double is really double.
1736 if (&S.Context.getFloatTypeSemantics(FromType) !=
1737 &S.Context.getFloatTypeSemantics(ToType)) {
1738 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1739 ToType == S.Context.LongDoubleTy) ||
1740 (FromType == S.Context.LongDoubleTy &&
1741 ToType == S.Context.Float128Ty));
1742 if (Float128AndLongDouble &&
1743 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001744 &llvm::APFloat::IEEEdouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001745 return false;
1746 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001747 // Floating point conversions (C++ 4.8).
1748 SCS.Second = ICK_Floating_Conversion;
1749 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001750 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001751 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001752 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001753 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001754 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001755 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001756 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001757 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001758 SCS.Second = ICK_Block_Pointer_Conversion;
1759 } else if (AllowObjCWritebackConversion &&
1760 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1761 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001762 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1763 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001764 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001765 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001766 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001767 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001768 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001769 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001770 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001771 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001772 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001773 SCS.Second = SecondICK;
1774 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001775 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001776 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001777 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001778 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001779 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001780 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1781 InOverloadResolution,
1782 SCS, CStyle)) {
1783 SCS.Second = ICK_TransparentUnionConversion;
1784 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001785 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1786 CStyle)) {
1787 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001788 // appropriately.
1789 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001790 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001791 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001792 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001793 SCS.Second = ICK_Zero_Event_Conversion;
1794 FromType = ToType;
Egor Churaev89831422016-12-23 14:55:49 +00001795 } else if (ToType->isQueueT() &&
1796 From->isIntegerConstantExpr(S.getASTContext()) &&
1797 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1798 SCS.Second = ICK_Zero_Queue_Conversion;
1799 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001800 } else {
1801 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001802 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001803 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001804 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001805
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001806 // The third conversion can be a function pointer conversion or a
1807 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001808 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001809 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1810 // Function pointer conversions (removing 'noexcept') including removal of
1811 // 'noreturn' (Clang extension).
1812 SCS.Third = ICK_Function_Conversion;
1813 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1814 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001815 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001816 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001817 FromType = ToType;
1818 } else {
1819 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001820 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001821 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001822
1823 // C++ [over.best.ics]p6:
1824 // [...] Any difference in top-level cv-qualification is
1825 // subsumed by the initialization itself and does not constitute
1826 // a conversion. [...]
1827 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1828 QualType CanonTo = S.Context.getCanonicalType(ToType);
1829 if (CanonFrom.getLocalUnqualifiedType()
1830 == CanonTo.getLocalUnqualifiedType() &&
1831 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1832 FromType = ToType;
1833 CanonFrom = CanonTo;
1834 }
1835
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001836 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001837
George Burgess IV45461812015-10-11 20:13:20 +00001838 if (CanonFrom == CanonTo)
1839 return true;
1840
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001841 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001842 // this is a bad conversion sequence, unless we're resolving an overload in C.
1843 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001844 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001845
George Burgess IV45461812015-10-11 20:13:20 +00001846 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001847 Sema::AssignConvertType Conv =
1848 S.CheckSingleAssignmentConstraints(ToType, ER,
1849 /*Diagnose=*/false,
1850 /*DiagnoseCFAudited=*/false,
1851 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001852 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001853 switch (Conv) {
1854 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001855 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001856 break;
1857 // For our purposes, discarding qualifiers is just as bad as using an
1858 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1859 // qualifiers, as well.
1860 case Sema::CompatiblePointerDiscardsQualifiers:
1861 case Sema::IncompatiblePointer:
1862 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001863 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001864 break;
1865 default:
George Burgess IV45461812015-10-11 20:13:20 +00001866 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001867 }
George Burgess IV45461812015-10-11 20:13:20 +00001868
George Burgess IV6098fd12016-09-03 00:28:25 +00001869 // First can only be an lvalue conversion, so we pretend that this was the
1870 // second conversion. First should already be valid from earlier in the
1871 // function.
1872 SCS.Second = SecondConv;
1873 SCS.setToType(1, ToType);
1874
1875 // Third is Identity, because Second should rank us worse than any other
1876 // conversion. This could also be ICK_Qualification, but it's simpler to just
1877 // lump everything in with the second conversion, and we don't gain anything
1878 // from making this ICK_Qualification.
1879 SCS.Third = ICK_Identity;
1880 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001881 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001882}
George Burgess IV2099b542016-09-02 22:59:57 +00001883
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001884static bool
1885IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1886 QualType &ToType,
1887 bool InOverloadResolution,
1888 StandardConversionSequence &SCS,
1889 bool CStyle) {
1890
1891 const RecordType *UT = ToType->getAsUnionType();
1892 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1893 return false;
1894 // The field to initialize within the transparent union.
1895 RecordDecl *UD = UT->getDecl();
1896 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001897 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001898 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1899 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001900 ToType = it->getType();
1901 return true;
1902 }
1903 }
1904 return false;
1905}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001906
1907/// IsIntegralPromotion - Determines whether the conversion from the
1908/// expression From (whose potentially-adjusted type is FromType) to
1909/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1910/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001911bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001912 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001913 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001914 if (!To) {
1915 return false;
1916 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001917
1918 // An rvalue of type char, signed char, unsigned char, short int, or
1919 // unsigned short int can be converted to an rvalue of type int if
1920 // int can represent all the values of the source type; otherwise,
1921 // the source rvalue can be converted to an rvalue of type unsigned
1922 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001923 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1924 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001925 if (// We can promote any signed, promotable integer type to an int
1926 (FromType->isSignedIntegerType() ||
1927 // We can promote any unsigned integer type whose size is
1928 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001929 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001930 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001931 }
1932
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001933 return To->getKind() == BuiltinType::UInt;
1934 }
1935
Richard Smithb9c5a602012-09-13 21:18:54 +00001936 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001937 // A prvalue of an unscoped enumeration type whose underlying type is not
1938 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1939 // following types that can represent all the values of the enumeration
1940 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1941 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001942 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001944 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945 // with lowest integer conversion rank (4.13) greater than the rank of long
1946 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001947 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001948 // C++11 [conv.prom]p4:
1949 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1950 // can be converted to a prvalue of its underlying type. Moreover, if
1951 // integral promotion can be applied to its underlying type, a prvalue of an
1952 // unscoped enumeration type whose underlying type is fixed can also be
1953 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001954 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1955 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1956 // provided for a scoped enumeration.
1957 if (FromEnumType->getDecl()->isScoped())
1958 return false;
1959
Richard Smithb9c5a602012-09-13 21:18:54 +00001960 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001961 // even if that's not the promoted type. Note that the check for promoting
1962 // the underlying type is based on the type alone, and does not consider
1963 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001964 if (FromEnumType->getDecl()->isFixed()) {
1965 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1966 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001967 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001968 }
1969
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001970 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001971 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001972 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001973 return Context.hasSameUnqualifiedType(
1974 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001975 }
John McCall56774992009-12-09 09:09:27 +00001976
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001977 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001978 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1979 // to an rvalue a prvalue of the first of the following types that can
1980 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001981 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001983 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001984 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001985 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001987 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001988 // Determine whether the type we're converting from is signed or
1989 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001990 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001991 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001993 // The types we'll try to promote to, in the appropriate
1994 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001995 QualType PromoteTypes[6] = {
1996 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001997 Context.LongTy, Context.UnsignedLongTy ,
1998 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001999 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002000 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002001 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2002 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002003 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002004 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2005 // We found the type that we can promote to. If this is the
2006 // type we wanted, we have a promotion. Otherwise, no
2007 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002008 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002009 }
2010 }
2011 }
2012
2013 // An rvalue for an integral bit-field (9.6) can be converted to an
2014 // rvalue of type int if int can represent all the values of the
2015 // bit-field; otherwise, it can be converted to unsigned int if
2016 // unsigned int can represent all the values of the bit-field. If
2017 // the bit-field is larger yet, no integral promotion applies to
2018 // it. If the bit-field has an enumerated type, it is treated as any
2019 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002020 // FIXME: We should delay checking of bit-fields until we actually perform the
2021 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00002022 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002023 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002024 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002025 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002026 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002027 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002028 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002029
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002030 // Are we promoting to an int from a bitfield that fits in an int?
2031 if (BitWidth < ToSize ||
2032 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2033 return To->getKind() == BuiltinType::Int;
2034 }
Mike Stump11289f42009-09-09 15:08:12 +00002035
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002036 // Are we promoting to an unsigned int from an unsigned bitfield
2037 // that fits into an unsigned int?
2038 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2039 return To->getKind() == BuiltinType::UInt;
2040 }
Mike Stump11289f42009-09-09 15:08:12 +00002041
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002042 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002043 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002044 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002045 }
Mike Stump11289f42009-09-09 15:08:12 +00002046
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002047 // An rvalue of type bool can be converted to an rvalue of type int,
2048 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002049 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002050 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002051 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002052
2053 return false;
2054}
2055
2056/// IsFloatingPointPromotion - Determines whether the conversion from
2057/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2058/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002059bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002060 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2061 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002062 /// An rvalue of type float can be converted to an rvalue of type
2063 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002064 if (FromBuiltin->getKind() == BuiltinType::Float &&
2065 ToBuiltin->getKind() == BuiltinType::Double)
2066 return true;
2067
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002068 // C99 6.3.1.5p1:
2069 // When a float is promoted to double or long double, or a
2070 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002071 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002072 (FromBuiltin->getKind() == BuiltinType::Float ||
2073 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002074 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2075 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002076 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002077
2078 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002079 if (!getLangOpts().NativeHalfType &&
2080 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002081 ToBuiltin->getKind() == BuiltinType::Float)
2082 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002083 }
2084
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002085 return false;
2086}
2087
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002088/// \brief Determine if a conversion is a complex promotion.
2089///
2090/// A complex promotion is defined as a complex -> complex conversion
2091/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002092/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002093bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002094 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002095 if (!FromComplex)
2096 return false;
2097
John McCall9dd450b2009-09-21 23:43:11 +00002098 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002099 if (!ToComplex)
2100 return false;
2101
2102 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002103 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002104 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002105 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002106}
2107
Douglas Gregor237f96c2008-11-26 23:31:11 +00002108/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2109/// the pointer type FromPtr to a pointer to type ToPointee, with the
2110/// same type qualifiers as FromPtr has on its pointee type. ToType,
2111/// if non-empty, will be a pointer to ToType that may or may not have
2112/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002113///
Mike Stump11289f42009-09-09 15:08:12 +00002114static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002115BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002116 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002117 ASTContext &Context,
2118 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002119 assert((FromPtr->getTypeClass() == Type::Pointer ||
2120 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2121 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002122
John McCall31168b02011-06-15 23:02:42 +00002123 /// Conversions to 'id' subsume cv-qualifier conversions.
2124 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002125 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002126
2127 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002128 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002129 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002130 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002131
John McCall31168b02011-06-15 23:02:42 +00002132 if (StripObjCLifetime)
2133 Quals.removeObjCLifetime();
2134
Mike Stump11289f42009-09-09 15:08:12 +00002135 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002136 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002137 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002138 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002139 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002140
2141 // Build a pointer to ToPointee. It has the right qualifiers
2142 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002143 if (isa<ObjCObjectPointerType>(ToType))
2144 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002145 return Context.getPointerType(ToPointee);
2146 }
2147
2148 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002149 QualType QualifiedCanonToPointee
2150 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002152 if (isa<ObjCObjectPointerType>(ToType))
2153 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2154 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002155}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002156
Mike Stump11289f42009-09-09 15:08:12 +00002157static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002158 bool InOverloadResolution,
2159 ASTContext &Context) {
2160 // Handle value-dependent integral null pointer constants correctly.
2161 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2162 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002163 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002164 return !InOverloadResolution;
2165
Douglas Gregor56751b52009-09-25 04:25:58 +00002166 return Expr->isNullPointerConstant(Context,
2167 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2168 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002169}
Mike Stump11289f42009-09-09 15:08:12 +00002170
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002171/// IsPointerConversion - Determines whether the conversion of the
2172/// expression From, which has the (possibly adjusted) type FromType,
2173/// can be converted to the type ToType via a pointer conversion (C++
2174/// 4.10). If so, returns true and places the converted type (that
2175/// might differ from ToType in its cv-qualifiers at some level) into
2176/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002177///
Douglas Gregora29dc052008-11-27 01:19:21 +00002178/// This routine also supports conversions to and from block pointers
2179/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2180/// pointers to interfaces. FIXME: Once we've determined the
2181/// appropriate overloading rules for Objective-C, we may want to
2182/// split the Objective-C checks into a different routine; however,
2183/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002184/// conversions, so for now they live here. IncompatibleObjC will be
2185/// set if the conversion is an allowed Objective-C conversion that
2186/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002187bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002188 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002189 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002190 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002191 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002192 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2193 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002194 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002195
Mike Stump11289f42009-09-09 15:08:12 +00002196 // Conversion from a null pointer constant to any Objective-C pointer type.
2197 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002198 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002199 ConvertedType = ToType;
2200 return true;
2201 }
2202
Douglas Gregor231d1c62008-11-27 00:15:41 +00002203 // Blocks: Block pointers can be converted to void*.
2204 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002205 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002206 ConvertedType = ToType;
2207 return true;
2208 }
2209 // Blocks: A null pointer constant can be converted to a block
2210 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002211 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002212 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002213 ConvertedType = ToType;
2214 return true;
2215 }
2216
Sebastian Redl576fd422009-05-10 18:38:11 +00002217 // If the left-hand-side is nullptr_t, the right side can be a null
2218 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002219 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002220 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002221 ConvertedType = ToType;
2222 return true;
2223 }
2224
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002225 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002226 if (!ToTypePtr)
2227 return false;
2228
2229 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002230 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002231 ConvertedType = ToType;
2232 return true;
2233 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002234
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002235 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002236 // , including objective-c pointers.
2237 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002238 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002239 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002240 ConvertedType = BuildSimilarlyQualifiedPointerType(
2241 FromType->getAs<ObjCObjectPointerType>(),
2242 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002243 ToType, Context);
2244 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002245 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002246 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002247 if (!FromTypePtr)
2248 return false;
2249
2250 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002251
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002252 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002253 // pointer conversion, so don't do all of the work below.
2254 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2255 return false;
2256
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002257 // An rvalue of type "pointer to cv T," where T is an object type,
2258 // can be converted to an rvalue of type "pointer to cv void" (C++
2259 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002260 if (FromPointeeType->isIncompleteOrObjectType() &&
2261 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002262 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002263 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002264 ToType, Context,
2265 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002266 return true;
2267 }
2268
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002269 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002270 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002271 ToPointeeType->isVoidType()) {
2272 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2273 ToPointeeType,
2274 ToType, Context);
2275 return true;
2276 }
2277
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002278 // When we're overloading in C, we allow a special kind of pointer
2279 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002280 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002281 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002282 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002283 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002284 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002285 return true;
2286 }
2287
Douglas Gregor5c407d92008-10-23 00:40:37 +00002288 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002289 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002290 // An rvalue of type "pointer to cv D," where D is a class type,
2291 // can be converted to an rvalue of type "pointer to cv B," where
2292 // B is a base class (clause 10) of D. If B is an inaccessible
2293 // (clause 11) or ambiguous (10.2) base class of D, a program that
2294 // necessitates this conversion is ill-formed. The result of the
2295 // conversion is a pointer to the base class sub-object of the
2296 // derived class object. The null pointer value is converted to
2297 // the null pointer value of the destination type.
2298 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002299 // Note that we do not check for ambiguity or inaccessibility
2300 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002301 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002302 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002303 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002304 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002305 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002306 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002307 ToType, Context);
2308 return true;
2309 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002310
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002311 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2312 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2313 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2314 ToPointeeType,
2315 ToType, Context);
2316 return true;
2317 }
2318
Douglas Gregora119f102008-12-19 19:13:09 +00002319 return false;
2320}
Douglas Gregoraec25842011-04-26 23:16:46 +00002321
2322/// \brief Adopt the given qualifiers for the given type.
2323static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2324 Qualifiers TQs = T.getQualifiers();
2325
2326 // Check whether qualifiers already match.
2327 if (TQs == Qs)
2328 return T;
2329
2330 if (Qs.compatiblyIncludes(TQs))
2331 return Context.getQualifiedType(T, Qs);
2332
2333 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2334}
Douglas Gregora119f102008-12-19 19:13:09 +00002335
2336/// isObjCPointerConversion - Determines whether this is an
2337/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2338/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002339bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002340 QualType& ConvertedType,
2341 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002342 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002343 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002344
Douglas Gregoraec25842011-04-26 23:16:46 +00002345 // The set of qualifiers on the type we're converting from.
2346 Qualifiers FromQualifiers = FromType.getQualifiers();
2347
Steve Naroff7cae42b2009-07-10 23:34:53 +00002348 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002349 const ObjCObjectPointerType* ToObjCPtr =
2350 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002351 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002352 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002353
Steve Naroff7cae42b2009-07-10 23:34:53 +00002354 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002355 // If the pointee types are the same (ignoring qualifications),
2356 // then this is not a pointer conversion.
2357 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2358 FromObjCPtr->getPointeeType()))
2359 return false;
2360
Douglas Gregorab209d82015-07-07 03:58:42 +00002361 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002362 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002363 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2364 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002365 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002366 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2367 FromObjCPtr->getPointeeType()))
2368 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002370 ToObjCPtr->getPointeeType(),
2371 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002372 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002373 return true;
2374 }
2375
2376 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2377 // Okay: this is some kind of implicit downcast of Objective-C
2378 // interfaces, which is permitted. However, we're going to
2379 // complain about it.
2380 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002381 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002382 ToObjCPtr->getPointeeType(),
2383 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002384 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002385 return true;
2386 }
Mike Stump11289f42009-09-09 15:08:12 +00002387 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002388 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002389 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002390 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002391 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002392 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002393 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002394 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002395 // to a block pointer type.
2396 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002397 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002398 return true;
2399 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002400 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002401 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002402 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002403 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002404 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002405 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002406 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002407 return true;
2408 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002409 else
Douglas Gregora119f102008-12-19 19:13:09 +00002410 return false;
2411
Douglas Gregor033f56d2008-12-23 00:53:59 +00002412 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002413 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002414 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002415 else if (const BlockPointerType *FromBlockPtr =
2416 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002417 FromPointeeType = FromBlockPtr->getPointeeType();
2418 else
Douglas Gregora119f102008-12-19 19:13:09 +00002419 return false;
2420
Douglas Gregora119f102008-12-19 19:13:09 +00002421 // If we have pointers to pointers, recursively check whether this
2422 // is an Objective-C conversion.
2423 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2424 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2425 IncompatibleObjC)) {
2426 // We always complain about this conversion.
2427 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002428 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002429 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002430 return true;
2431 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002432 // Allow conversion of pointee being objective-c pointer to another one;
2433 // as in I* to id.
2434 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2435 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2436 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2437 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002438
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002439 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002440 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002441 return true;
2442 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002443
Douglas Gregor033f56d2008-12-23 00:53:59 +00002444 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002445 // differences in the argument and result types are in Objective-C
2446 // pointer conversions. If so, we permit the conversion (but
2447 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002448 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002449 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002450 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002451 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002452 if (FromFunctionType && ToFunctionType) {
2453 // If the function types are exactly the same, this isn't an
2454 // Objective-C pointer conversion.
2455 if (Context.getCanonicalType(FromPointeeType)
2456 == Context.getCanonicalType(ToPointeeType))
2457 return false;
2458
2459 // Perform the quick checks that will tell us whether these
2460 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002461 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002462 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2463 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2464 return false;
2465
2466 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002467 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2468 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002469 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002470 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2471 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002472 ConvertedType, IncompatibleObjC)) {
2473 // Okay, we have an Objective-C pointer conversion.
2474 HasObjCConversion = true;
2475 } else {
2476 // Function types are too different. Abort.
2477 return false;
2478 }
Mike Stump11289f42009-09-09 15:08:12 +00002479
Douglas Gregora119f102008-12-19 19:13:09 +00002480 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002481 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002482 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002483 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2484 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002485 if (Context.getCanonicalType(FromArgType)
2486 == Context.getCanonicalType(ToArgType)) {
2487 // Okay, the types match exactly. Nothing to do.
2488 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2489 ConvertedType, IncompatibleObjC)) {
2490 // Okay, we have an Objective-C pointer conversion.
2491 HasObjCConversion = true;
2492 } else {
2493 // Argument types are too different. Abort.
2494 return false;
2495 }
2496 }
2497
2498 if (HasObjCConversion) {
2499 // We had an Objective-C conversion. Allow this pointer
2500 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002501 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002502 IncompatibleObjC = true;
2503 return true;
2504 }
2505 }
2506
Sebastian Redl72b597d2009-01-25 19:43:20 +00002507 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002508}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002509
John McCall31168b02011-06-15 23:02:42 +00002510/// \brief Determine whether this is an Objective-C writeback conversion,
2511/// used for parameter passing when performing automatic reference counting.
2512///
2513/// \param FromType The type we're converting form.
2514///
2515/// \param ToType The type we're converting to.
2516///
2517/// \param ConvertedType The type that will be produced after applying
2518/// this conversion.
2519bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2520 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002521 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002522 Context.hasSameUnqualifiedType(FromType, ToType))
2523 return false;
2524
2525 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2526 QualType ToPointee;
2527 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2528 ToPointee = ToPointer->getPointeeType();
2529 else
2530 return false;
2531
2532 Qualifiers ToQuals = ToPointee.getQualifiers();
2533 if (!ToPointee->isObjCLifetimeType() ||
2534 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002535 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002536 return false;
2537
2538 // Argument must be a pointer to __strong to __weak.
2539 QualType FromPointee;
2540 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2541 FromPointee = FromPointer->getPointeeType();
2542 else
2543 return false;
2544
2545 Qualifiers FromQuals = FromPointee.getQualifiers();
2546 if (!FromPointee->isObjCLifetimeType() ||
2547 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2548 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2549 return false;
2550
2551 // Make sure that we have compatible qualifiers.
2552 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2553 if (!ToQuals.compatiblyIncludes(FromQuals))
2554 return false;
2555
2556 // Remove qualifiers from the pointee type we're converting from; they
2557 // aren't used in the compatibility check belong, and we'll be adding back
2558 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2559 FromPointee = FromPointee.getUnqualifiedType();
2560
2561 // The unqualified form of the pointee types must be compatible.
2562 ToPointee = ToPointee.getUnqualifiedType();
2563 bool IncompatibleObjC;
2564 if (Context.typesAreCompatible(FromPointee, ToPointee))
2565 FromPointee = ToPointee;
2566 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2567 IncompatibleObjC))
2568 return false;
2569
2570 /// \brief Construct the type we're converting to, which is a pointer to
2571 /// __autoreleasing pointee.
2572 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2573 ConvertedType = Context.getPointerType(FromPointee);
2574 return true;
2575}
2576
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002577bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2578 QualType& ConvertedType) {
2579 QualType ToPointeeType;
2580 if (const BlockPointerType *ToBlockPtr =
2581 ToType->getAs<BlockPointerType>())
2582 ToPointeeType = ToBlockPtr->getPointeeType();
2583 else
2584 return false;
2585
2586 QualType FromPointeeType;
2587 if (const BlockPointerType *FromBlockPtr =
2588 FromType->getAs<BlockPointerType>())
2589 FromPointeeType = FromBlockPtr->getPointeeType();
2590 else
2591 return false;
2592 // We have pointer to blocks, check whether the only
2593 // differences in the argument and result types are in Objective-C
2594 // pointer conversions. If so, we permit the conversion.
2595
2596 const FunctionProtoType *FromFunctionType
2597 = FromPointeeType->getAs<FunctionProtoType>();
2598 const FunctionProtoType *ToFunctionType
2599 = ToPointeeType->getAs<FunctionProtoType>();
2600
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002601 if (!FromFunctionType || !ToFunctionType)
2602 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002603
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002604 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002605 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002606
2607 // Perform the quick checks that will tell us whether these
2608 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002609 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002610 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2611 return false;
2612
2613 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2614 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2615 if (FromEInfo != ToEInfo)
2616 return false;
2617
2618 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002619 if (Context.hasSameType(FromFunctionType->getReturnType(),
2620 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002621 // Okay, the types match exactly. Nothing to do.
2622 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002623 QualType RHS = FromFunctionType->getReturnType();
2624 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002625 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002626 !RHS.hasQualifiers() && LHS.hasQualifiers())
2627 LHS = LHS.getUnqualifiedType();
2628
2629 if (Context.hasSameType(RHS,LHS)) {
2630 // OK exact match.
2631 } else if (isObjCPointerConversion(RHS, LHS,
2632 ConvertedType, IncompatibleObjC)) {
2633 if (IncompatibleObjC)
2634 return false;
2635 // Okay, we have an Objective-C pointer conversion.
2636 }
2637 else
2638 return false;
2639 }
2640
2641 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002642 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002643 ArgIdx != NumArgs; ++ArgIdx) {
2644 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002645 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2646 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002647 if (Context.hasSameType(FromArgType, ToArgType)) {
2648 // Okay, the types match exactly. Nothing to do.
2649 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2650 ConvertedType, IncompatibleObjC)) {
2651 if (IncompatibleObjC)
2652 return false;
2653 // Okay, we have an Objective-C pointer conversion.
2654 } else
2655 // Argument types are too different. Abort.
2656 return false;
2657 }
John McCall18afab72016-03-01 00:49:02 +00002658 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2659 ToFunctionType))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002660 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002661
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002662 ConvertedType = ToType;
2663 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002664}
2665
Richard Trieucaff2472011-11-23 22:32:32 +00002666enum {
2667 ft_default,
2668 ft_different_class,
2669 ft_parameter_arity,
2670 ft_parameter_mismatch,
2671 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002672 ft_qualifer_mismatch,
2673 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002674};
2675
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002676/// Attempts to get the FunctionProtoType from a Type. Handles
2677/// MemberFunctionPointers properly.
2678static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2679 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2680 return FPT;
2681
2682 if (auto *MPT = FromType->getAs<MemberPointerType>())
2683 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2684
2685 return nullptr;
2686}
2687
Richard Trieucaff2472011-11-23 22:32:32 +00002688/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2689/// function types. Catches different number of parameter, mismatch in
2690/// parameter types, and different return types.
2691void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2692 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002693 // If either type is not valid, include no extra info.
2694 if (FromType.isNull() || ToType.isNull()) {
2695 PDiag << ft_default;
2696 return;
2697 }
2698
Richard Trieucaff2472011-11-23 22:32:32 +00002699 // Get the function type from the pointers.
2700 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2701 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2702 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002703 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002704 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2705 << QualType(FromMember->getClass(), 0);
2706 return;
2707 }
2708 FromType = FromMember->getPointeeType();
2709 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002710 }
2711
Richard Trieu96ed5b62011-12-13 23:19:45 +00002712 if (FromType->isPointerType())
2713 FromType = FromType->getPointeeType();
2714 if (ToType->isPointerType())
2715 ToType = ToType->getPointeeType();
2716
2717 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002718 FromType = FromType.getNonReferenceType();
2719 ToType = ToType.getNonReferenceType();
2720
Richard Trieucaff2472011-11-23 22:32:32 +00002721 // Don't print extra info for non-specialized template functions.
2722 if (FromType->isInstantiationDependentType() &&
2723 !FromType->getAs<TemplateSpecializationType>()) {
2724 PDiag << ft_default;
2725 return;
2726 }
2727
Richard Trieu96ed5b62011-12-13 23:19:45 +00002728 // No extra info for same types.
2729 if (Context.hasSameType(FromType, ToType)) {
2730 PDiag << ft_default;
2731 return;
2732 }
2733
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002734 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2735 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002736
2737 // Both types need to be function types.
2738 if (!FromFunction || !ToFunction) {
2739 PDiag << ft_default;
2740 return;
2741 }
2742
Alp Toker9cacbab2014-01-20 20:26:09 +00002743 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2744 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2745 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002746 return;
2747 }
2748
2749 // Handle different parameter types.
2750 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002751 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002752 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002753 << ToFunction->getParamType(ArgPos)
2754 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002755 return;
2756 }
2757
2758 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002759 if (!Context.hasSameType(FromFunction->getReturnType(),
2760 ToFunction->getReturnType())) {
2761 PDiag << ft_return_type << ToFunction->getReturnType()
2762 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002763 return;
2764 }
2765
2766 unsigned FromQuals = FromFunction->getTypeQuals(),
2767 ToQuals = ToFunction->getTypeQuals();
2768 if (FromQuals != ToQuals) {
2769 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2770 return;
2771 }
2772
Richard Smith3c4f8d22016-10-16 17:54:23 +00002773 // Handle exception specification differences on canonical type (in C++17
2774 // onwards).
2775 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2776 ->isNothrow(Context) !=
2777 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2778 ->isNothrow(Context)) {
2779 PDiag << ft_noexcept;
2780 return;
2781 }
2782
Richard Trieucaff2472011-11-23 22:32:32 +00002783 // Unable to find a difference, so add no extra info.
2784 PDiag << ft_default;
2785}
2786
Alp Toker9cacbab2014-01-20 20:26:09 +00002787/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002788/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002789/// they have same number of arguments. If the parameters are different,
2790/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002791bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2792 const FunctionProtoType *NewType,
2793 unsigned *ArgPos) {
2794 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2795 N = NewType->param_type_begin(),
2796 E = OldType->param_type_end();
2797 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002798 if (!Context.hasSameType(O->getUnqualifiedType(),
2799 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002800 if (ArgPos)
2801 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002802 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002803 }
2804 }
2805 return true;
2806}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002807
Douglas Gregor39c16d42008-10-24 04:54:22 +00002808/// CheckPointerConversion - Check the pointer conversion from the
2809/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002810/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002811/// conversions for which IsPointerConversion has already returned
2812/// true. It returns true and produces a diagnostic if there was an
2813/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002814bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002815 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002816 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002817 bool IgnoreBaseAccess,
2818 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002819 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002820 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002821
John McCall8cb679e2010-11-15 09:13:47 +00002822 Kind = CK_BitCast;
2823
George Burgess IV60bc9722016-01-13 23:36:34 +00002824 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002825 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002826 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002827 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2828 DiagRuntimeBehavior(From->getExprLoc(), From,
2829 PDiag(diag::warn_impcast_bool_to_null_pointer)
2830 << ToType << From->getSourceRange());
2831 else if (!isUnevaluatedContext())
2832 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2833 << ToType << From->getSourceRange();
2834 }
John McCall9320b872011-09-09 05:25:32 +00002835 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2836 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002837 QualType FromPointeeType = FromPtrType->getPointeeType(),
2838 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002839
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002840 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2841 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002842 // We must have a derived-to-base conversion. Check an
2843 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002844 unsigned InaccessibleID = 0;
2845 unsigned AmbigiousID = 0;
2846 if (Diagnose) {
2847 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2848 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2849 }
2850 if (CheckDerivedToBaseConversion(
2851 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2852 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2853 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002854 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002855
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002856 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002857 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002858 }
David Majnemer6bf02822015-10-31 08:42:14 +00002859
George Burgess IV60bc9722016-01-13 23:36:34 +00002860 if (Diagnose && !IsCStyleOrFunctionalCast &&
2861 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002862 assert(getLangOpts().MSVCCompat &&
2863 "this should only be possible with MSVCCompat!");
2864 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2865 << From->getSourceRange();
2866 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002867 }
John McCall9320b872011-09-09 05:25:32 +00002868 } else if (const ObjCObjectPointerType *ToPtrType =
2869 ToType->getAs<ObjCObjectPointerType>()) {
2870 if (const ObjCObjectPointerType *FromPtrType =
2871 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002872 // Objective-C++ conversions are always okay.
2873 // FIXME: We should have a different class of conversions for the
2874 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002875 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002876 return false;
John McCall9320b872011-09-09 05:25:32 +00002877 } else if (FromType->isBlockPointerType()) {
2878 Kind = CK_BlockPointerToObjCPointerCast;
2879 } else {
2880 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002881 }
John McCall9320b872011-09-09 05:25:32 +00002882 } else if (ToType->isBlockPointerType()) {
2883 if (!FromType->isBlockPointerType())
2884 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002885 }
John McCall8cb679e2010-11-15 09:13:47 +00002886
2887 // We shouldn't fall into this case unless it's valid for other
2888 // reasons.
2889 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2890 Kind = CK_NullToPointer;
2891
Douglas Gregor39c16d42008-10-24 04:54:22 +00002892 return false;
2893}
2894
Sebastian Redl72b597d2009-01-25 19:43:20 +00002895/// IsMemberPointerConversion - Determines whether the conversion of the
2896/// expression From, which has the (possibly adjusted) type FromType, can be
2897/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2898/// If so, returns true and places the converted type (that might differ from
2899/// ToType in its cv-qualifiers at some level) into ConvertedType.
2900bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002901 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002902 bool InOverloadResolution,
2903 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002904 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002905 if (!ToTypePtr)
2906 return false;
2907
2908 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002909 if (From->isNullPointerConstant(Context,
2910 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2911 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002912 ConvertedType = ToType;
2913 return true;
2914 }
2915
2916 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002917 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002918 if (!FromTypePtr)
2919 return false;
2920
2921 // A pointer to member of B can be converted to a pointer to member of D,
2922 // where D is derived from B (C++ 4.11p2).
2923 QualType FromClass(FromTypePtr->getClass(), 0);
2924 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002925
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002926 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002927 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002928 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2929 ToClass.getTypePtr());
2930 return true;
2931 }
2932
2933 return false;
2934}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002935
Sebastian Redl72b597d2009-01-25 19:43:20 +00002936/// CheckMemberPointerConversion - Check the member pointer conversion from the
2937/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002938/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002939/// for which IsMemberPointerConversion has already returned true. It returns
2940/// true and produces a diagnostic if there was an error, or returns false
2941/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002942bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002943 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002944 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002945 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002946 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002947 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002948 if (!FromPtrType) {
2949 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002950 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002951 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002952 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002953 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002954 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002955 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002956
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002957 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002958 assert(ToPtrType && "No member pointer cast has a target type "
2959 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002960
Sebastian Redled8f2002009-01-28 18:33:18 +00002961 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2962 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002963
Sebastian Redled8f2002009-01-28 18:33:18 +00002964 // FIXME: What about dependent types?
2965 assert(FromClass->isRecordType() && "Pointer into non-class.");
2966 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002967
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002968 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002969 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002970 bool DerivationOkay =
2971 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002972 assert(DerivationOkay &&
2973 "Should not have been called if derivation isn't OK.");
2974 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002975
Sebastian Redled8f2002009-01-28 18:33:18 +00002976 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2977 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002978 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2979 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2980 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2981 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002982 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002983
Douglas Gregor89ee6822009-02-28 01:32:25 +00002984 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002985 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2986 << FromClass << ToClass << QualType(VBase, 0)
2987 << From->getSourceRange();
2988 return true;
2989 }
2990
John McCall5b0829a2010-02-10 09:31:12 +00002991 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002992 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2993 Paths.front(),
2994 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002995
Anders Carlssond7923c62009-08-22 23:33:40 +00002996 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002997 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002998 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002999 return false;
3000}
3001
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003002/// Determine whether the lifetime conversion between the two given
3003/// qualifiers sets is nontrivial.
3004static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3005 Qualifiers ToQuals) {
3006 // Converting anything to const __unsafe_unretained is trivial.
3007 if (ToQuals.hasConst() &&
3008 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3009 return false;
3010
3011 return true;
3012}
3013
Douglas Gregor9a657932008-10-21 23:43:52 +00003014/// IsQualificationConversion - Determines whether the conversion from
3015/// an rvalue of type FromType to ToType is a qualification conversion
3016/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003017///
3018/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3019/// when the qualification conversion involves a change in the Objective-C
3020/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003021bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003022Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003023 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003024 FromType = Context.getCanonicalType(FromType);
3025 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003026 ObjCLifetimeConversion = false;
3027
Douglas Gregor9a657932008-10-21 23:43:52 +00003028 // If FromType and ToType are the same type, this is not a
3029 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003030 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003031 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003032
Douglas Gregor9a657932008-10-21 23:43:52 +00003033 // (C++ 4.4p4):
3034 // A conversion can add cv-qualifiers at levels other than the first
3035 // in multi-level pointers, subject to the following rules: [...]
3036 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003037 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003038 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003039 // Within each iteration of the loop, we check the qualifiers to
3040 // determine if this still looks like a qualification
3041 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003042 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003043 // until there are no more pointers or pointers-to-members left to
3044 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003045 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003046
Douglas Gregor90609aa2011-04-25 18:40:17 +00003047 Qualifiers FromQuals = FromType.getQualifiers();
3048 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003049
3050 // Ignore __unaligned qualifier if this type is void.
3051 if (ToType.getUnqualifiedType()->isVoidType())
3052 FromQuals.removeUnaligned();
Douglas Gregor90609aa2011-04-25 18:40:17 +00003053
John McCall31168b02011-06-15 23:02:42 +00003054 // Objective-C ARC:
3055 // Check Objective-C lifetime conversions.
3056 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3057 UnwrappedAnyPointer) {
3058 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003059 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3060 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003061 FromQuals.removeObjCLifetime();
3062 ToQuals.removeObjCLifetime();
3063 } else {
3064 // Qualification conversions cannot cast between different
3065 // Objective-C lifetime qualifiers.
3066 return false;
3067 }
3068 }
3069
Douglas Gregorf30053d2011-05-08 06:09:53 +00003070 // Allow addition/removal of GC attributes but not changing GC attributes.
3071 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3072 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3073 FromQuals.removeObjCGCAttr();
3074 ToQuals.removeObjCGCAttr();
3075 }
3076
Douglas Gregor9a657932008-10-21 23:43:52 +00003077 // -- for every j > 0, if const is in cv 1,j then const is in cv
3078 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003079 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003080 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003081
Douglas Gregor9a657932008-10-21 23:43:52 +00003082 // -- if the cv 1,j and cv 2,j are different, then const is in
3083 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003084 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003085 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003086 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003087
Douglas Gregor9a657932008-10-21 23:43:52 +00003088 // Keep track of whether all prior cv-qualifiers in the "to" type
3089 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003090 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003091 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003092 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003093
3094 // We are left with FromType and ToType being the pointee types
3095 // after unwrapping the original FromType and ToType the same number
3096 // of types. If we unwrapped any pointers, and if FromType and
3097 // ToType have the same unqualified type (since we checked
3098 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003099 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003100}
3101
Douglas Gregorc79862f2012-04-12 17:51:55 +00003102/// \brief - Determine whether this is a conversion from a scalar type to an
3103/// atomic type.
3104///
3105/// If successful, updates \c SCS's second and third steps in the conversion
3106/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003107static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3108 bool InOverloadResolution,
3109 StandardConversionSequence &SCS,
3110 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003111 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3112 if (!ToAtomic)
3113 return false;
3114
3115 StandardConversionSequence InnerSCS;
3116 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3117 InOverloadResolution, InnerSCS,
3118 CStyle, /*AllowObjCWritebackConversion=*/false))
3119 return false;
3120
3121 SCS.Second = InnerSCS.Second;
3122 SCS.setToType(1, InnerSCS.getToType(1));
3123 SCS.Third = InnerSCS.Third;
3124 SCS.QualificationIncludesObjCLifetime
3125 = InnerSCS.QualificationIncludesObjCLifetime;
3126 SCS.setToType(2, InnerSCS.getToType(2));
3127 return true;
3128}
3129
Sebastian Redle5417162012-03-27 18:33:03 +00003130static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3131 CXXConstructorDecl *Constructor,
3132 QualType Type) {
3133 const FunctionProtoType *CtorType =
3134 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003135 if (CtorType->getNumParams() > 0) {
3136 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003137 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3138 return true;
3139 }
3140 return false;
3141}
3142
Sebastian Redl82ace982012-02-11 23:51:08 +00003143static OverloadingResult
3144IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3145 CXXRecordDecl *To,
3146 UserDefinedConversionSequence &User,
3147 OverloadCandidateSet &CandidateSet,
3148 bool AllowExplicit) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003149 for (auto *D : S.LookupConstructors(To)) {
3150 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003151 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003152 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003153
Richard Smithc2bebe92016-05-11 20:37:46 +00003154 bool Usable = !Info.Constructor->isInvalidDecl() &&
3155 S.isInitListConstructor(Info.Constructor) &&
3156 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003157 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003158 // If the first argument is (a reference to) the target type,
3159 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003160 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3161 S.Context, Info.Constructor, ToType);
3162 if (Info.ConstructorTmpl)
3163 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3164 /*ExplicitArgs*/ nullptr, From,
3165 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003166 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003167 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3168 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003169 }
3170 }
3171
3172 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3173
3174 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003175 switch (auto Result =
3176 CandidateSet.BestViableFunction(S, From->getLocStart(),
3177 Best, true)) {
3178 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003179 case OR_Success: {
3180 // Record the standard conversion we used and the conversion function.
3181 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003182 QualType ThisType = Constructor->getThisType(S.Context);
3183 // Initializer lists don't have conversions as such.
3184 User.Before.setAsIdentityConversion();
3185 User.HadMultipleCandidates = HadMultipleCandidates;
3186 User.ConversionFunction = Constructor;
3187 User.FoundConversionFunction = Best->FoundDecl;
3188 User.After.setAsIdentityConversion();
3189 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3190 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003191 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003192 }
3193
3194 case OR_No_Viable_Function:
3195 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003196 case OR_Ambiguous:
3197 return OR_Ambiguous;
3198 }
3199
3200 llvm_unreachable("Invalid OverloadResult!");
3201}
3202
Douglas Gregor576e98c2009-01-30 23:27:23 +00003203/// Determines whether there is a user-defined conversion sequence
3204/// (C++ [over.ics.user]) that converts expression From to the type
3205/// ToType. If such a conversion exists, User will contain the
3206/// user-defined conversion sequence that performs such a conversion
3207/// and this routine will return true. Otherwise, this routine returns
3208/// false and User is unspecified.
3209///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003210/// \param AllowExplicit true if the conversion should consider C++0x
3211/// "explicit" conversion functions as well as non-explicit conversion
3212/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003213///
3214/// \param AllowObjCConversionOnExplicit true if the conversion should
3215/// allow an extra Objective-C pointer conversion on uses of explicit
3216/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003217static OverloadingResult
3218IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003219 UserDefinedConversionSequence &User,
3220 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003221 bool AllowExplicit,
3222 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003223 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003224
Douglas Gregor5ab11652010-04-17 22:01:05 +00003225 // Whether we will only visit constructors.
3226 bool ConstructorsOnly = false;
3227
3228 // If the type we are conversion to is a class type, enumerate its
3229 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003230 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003231 // C++ [over.match.ctor]p1:
3232 // When objects of class type are direct-initialized (8.5), or
3233 // copy-initialized from an expression of the same or a
3234 // derived class type (8.5), overload resolution selects the
3235 // constructor. [...] For copy-initialization, the candidate
3236 // functions are all the converting constructors (12.3.1) of
3237 // that class. The argument list is the expression-list within
3238 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003239 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003240 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003241 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003242 ConstructorsOnly = true;
3243
Richard Smithdb0ac552015-12-18 22:40:25 +00003244 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003245 // We're not going to find any constructors.
3246 } else if (CXXRecordDecl *ToRecordDecl
3247 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003248
3249 Expr **Args = &From;
3250 unsigned NumArgs = 1;
3251 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003252 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003253 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003254 OverloadingResult Result = IsInitializerListConstructorConversion(
3255 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3256 if (Result != OR_No_Viable_Function)
3257 return Result;
3258 // Never mind.
3259 CandidateSet.clear();
3260
3261 // If we're list-initializing, we pass the individual elements as
3262 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003263 Args = InitList->getInits();
3264 NumArgs = InitList->getNumInits();
3265 ListInitializing = true;
3266 }
3267
Richard Smithc2bebe92016-05-11 20:37:46 +00003268 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3269 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003270 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003271 continue;
John McCalla0296f72010-03-19 07:35:19 +00003272
Richard Smithc2bebe92016-05-11 20:37:46 +00003273 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003274 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003275 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003276 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003277 Usable = Usable &&
3278 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003279 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003280 bool SuppressUserConversions = !ConstructorsOnly;
3281 if (SuppressUserConversions && ListInitializing) {
3282 SuppressUserConversions = false;
3283 if (NumArgs == 1) {
3284 // If the first argument is (a reference to) the target type,
3285 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003286 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003287 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003288 }
3289 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003290 if (Info.ConstructorTmpl)
3291 S.AddTemplateOverloadCandidate(
3292 Info.ConstructorTmpl, Info.FoundDecl,
3293 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3294 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003295 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003296 // Allow one user-defined conversion when user specifies a
3297 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003298 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003299 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003300 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003301 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003302 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003303 }
3304 }
3305
Douglas Gregor5ab11652010-04-17 22:01:05 +00003306 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003307 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003308 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003309 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003310 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003311 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003312 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003313 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3314 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003315 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3316 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003317 DeclAccessPair FoundDecl = I.getPair();
3318 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003319 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3320 if (isa<UsingShadowDecl>(D))
3321 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3322
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003323 CXXConversionDecl *Conv;
3324 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003325 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3326 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003327 else
John McCallda4458e2010-03-31 01:36:47 +00003328 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003329
3330 if (AllowExplicit || !Conv->isExplicit()) {
3331 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003332 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3333 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003334 CandidateSet,
3335 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003336 else
John McCall5c32be02010-08-24 20:38:10 +00003337 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003338 From, ToType, CandidateSet,
3339 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003340 }
3341 }
3342 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003343 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003344
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003345 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3346
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003347 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003348 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3349 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003350 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003351 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003352 // Record the standard conversion we used and the conversion function.
3353 if (CXXConstructorDecl *Constructor
3354 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3355 // C++ [over.ics.user]p1:
3356 // If the user-defined conversion is specified by a
3357 // constructor (12.3.1), the initial standard conversion
3358 // sequence converts the source type to the type required by
3359 // the argument of the constructor.
3360 //
3361 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003362 if (isa<InitListExpr>(From)) {
3363 // Initializer lists don't have conversions as such.
3364 User.Before.setAsIdentityConversion();
3365 } else {
3366 if (Best->Conversions[0].isEllipsis())
3367 User.EllipsisConversion = true;
3368 else {
3369 User.Before = Best->Conversions[0].Standard;
3370 User.EllipsisConversion = false;
3371 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003372 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003373 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003374 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003375 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003376 User.After.setAsIdentityConversion();
3377 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3378 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003379 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003380 }
3381 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003382 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3383 // C++ [over.ics.user]p1:
3384 //
3385 // [...] If the user-defined conversion is specified by a
3386 // conversion function (12.3.2), the initial standard
3387 // conversion sequence converts the source type to the
3388 // implicit object parameter of the conversion function.
3389 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003390 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003391 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003392 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003393 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003394
John McCall5c32be02010-08-24 20:38:10 +00003395 // C++ [over.ics.user]p2:
3396 // The second standard conversion sequence converts the
3397 // result of the user-defined conversion to the target type
3398 // for the sequence. Since an implicit conversion sequence
3399 // is an initialization, the special rules for
3400 // initialization by user-defined conversion apply when
3401 // selecting the best user-defined conversion for a
3402 // user-defined conversion sequence (see 13.3.3 and
3403 // 13.3.3.1).
3404 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003405 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003406 }
David Blaikie8a40f702012-01-17 06:56:22 +00003407 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003408
John McCall5c32be02010-08-24 20:38:10 +00003409 case OR_No_Viable_Function:
3410 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411
John McCall5c32be02010-08-24 20:38:10 +00003412 case OR_Ambiguous:
3413 return OR_Ambiguous;
3414 }
3415
David Blaikie8a40f702012-01-17 06:56:22 +00003416 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003417}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003418
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003419bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003420Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003421 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003422 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3423 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003425 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003426 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003427 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003428 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3429 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003430 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003431 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003432 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003433 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003434 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003435 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003436 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003437 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003438 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003440}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003441
Douglas Gregor2837aa22012-02-22 17:32:19 +00003442/// \brief Compare the user-defined conversion functions or constructors
3443/// of two user-defined conversion sequences to determine whether any ordering
3444/// is possible.
3445static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003446compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003447 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003448 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003449 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003450
Douglas Gregor2837aa22012-02-22 17:32:19 +00003451 // Objective-C++:
3452 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003453 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003454 // respectively, always prefer the conversion to a function pointer,
3455 // because the function pointer is more lightweight and is more likely
3456 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003457 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003458 if (!Conv1)
3459 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003460
Douglas Gregor2837aa22012-02-22 17:32:19 +00003461 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3462 if (!Conv2)
3463 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003464
Douglas Gregor2837aa22012-02-22 17:32:19 +00003465 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3466 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3467 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3468 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003469 return Block1 ? ImplicitConversionSequence::Worse
3470 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003471 }
3472
3473 return ImplicitConversionSequence::Indistinguishable;
3474}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003475
3476static bool hasDeprecatedStringLiteralToCharPtrConversion(
3477 const ImplicitConversionSequence &ICS) {
3478 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3479 (ICS.isUserDefined() &&
3480 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3481}
3482
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003483/// CompareImplicitConversionSequences - Compare two implicit
3484/// conversion sequences to determine whether one is better than the
3485/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003486static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003487CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003488 const ImplicitConversionSequence& ICS1,
3489 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003490{
3491 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3492 // conversion sequences (as defined in 13.3.3.1)
3493 // -- a standard conversion sequence (13.3.3.1.1) is a better
3494 // conversion sequence than a user-defined conversion sequence or
3495 // an ellipsis conversion sequence, and
3496 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3497 // conversion sequence than an ellipsis conversion sequence
3498 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003499 //
John McCall0d1da222010-01-12 00:44:57 +00003500 // C++0x [over.best.ics]p10:
3501 // For the purpose of ranking implicit conversion sequences as
3502 // described in 13.3.3.2, the ambiguous conversion sequence is
3503 // treated as a user-defined sequence that is indistinguishable
3504 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003505
3506 // String literal to 'char *' conversion has been deprecated in C++03. It has
3507 // been removed from C++11. We still accept this conversion, if it happens at
3508 // the best viable function. Otherwise, this conversion is considered worse
3509 // than ellipsis conversion. Consider this as an extension; this is not in the
3510 // standard. For example:
3511 //
3512 // int &f(...); // #1
3513 // void f(char*); // #2
3514 // void g() { int &r = f("foo"); }
3515 //
3516 // In C++03, we pick #2 as the best viable function.
3517 // In C++11, we pick #1 as the best viable function, because ellipsis
3518 // conversion is better than string-literal to char* conversion (since there
3519 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3520 // convert arguments, #2 would be the best viable function in C++11.
3521 // If the best viable function has this conversion, a warning will be issued
3522 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3523
3524 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3525 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3526 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3527 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3528 ? ImplicitConversionSequence::Worse
3529 : ImplicitConversionSequence::Better;
3530
Douglas Gregor5ab11652010-04-17 22:01:05 +00003531 if (ICS1.getKindRank() < ICS2.getKindRank())
3532 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003533 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003534 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003535
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003536 // The following checks require both conversion sequences to be of
3537 // the same kind.
3538 if (ICS1.getKind() != ICS2.getKind())
3539 return ImplicitConversionSequence::Indistinguishable;
3540
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003541 ImplicitConversionSequence::CompareKind Result =
3542 ImplicitConversionSequence::Indistinguishable;
3543
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003544 // Two implicit conversion sequences of the same form are
3545 // indistinguishable conversion sequences unless one of the
3546 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003547
3548 // List-initialization sequence L1 is a better conversion sequence than
3549 // list-initialization sequence L2 if:
3550 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3551 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003552 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003553 // and N1 is smaller than N2.,
3554 // even if one of the other rules in this paragraph would otherwise apply.
3555 if (!ICS1.isBad()) {
3556 if (ICS1.isStdInitializerListElement() &&
3557 !ICS2.isStdInitializerListElement())
3558 return ImplicitConversionSequence::Better;
3559 if (!ICS1.isStdInitializerListElement() &&
3560 ICS2.isStdInitializerListElement())
3561 return ImplicitConversionSequence::Worse;
3562 }
3563
John McCall0d1da222010-01-12 00:44:57 +00003564 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003565 // Standard conversion sequence S1 is a better conversion sequence than
3566 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003567 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003568 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003569 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003570 // User-defined conversion sequence U1 is a better conversion
3571 // sequence than another user-defined conversion sequence U2 if
3572 // they contain the same user-defined conversion function or
3573 // constructor and if the second standard conversion sequence of
3574 // U1 is better than the second standard conversion sequence of
3575 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003576 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003577 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003578 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003579 ICS1.UserDefined.After,
3580 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003581 else
3582 Result = compareConversionFunctions(S,
3583 ICS1.UserDefined.ConversionFunction,
3584 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003585 }
3586
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003587 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003588}
3589
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003590static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3591 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3592 Qualifiers Quals;
3593 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003594 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003597 return Context.hasSameUnqualifiedType(T1, T2);
3598}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003600// Per 13.3.3.2p3, compare the given standard conversion sequences to
3601// determine if one is a proper subset of the other.
3602static ImplicitConversionSequence::CompareKind
3603compareStandardConversionSubsets(ASTContext &Context,
3604 const StandardConversionSequence& SCS1,
3605 const StandardConversionSequence& SCS2) {
3606 ImplicitConversionSequence::CompareKind Result
3607 = ImplicitConversionSequence::Indistinguishable;
3608
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003609 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003610 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003611 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3612 return ImplicitConversionSequence::Better;
3613 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3614 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003616 if (SCS1.Second != SCS2.Second) {
3617 if (SCS1.Second == ICK_Identity)
3618 Result = ImplicitConversionSequence::Better;
3619 else if (SCS2.Second == ICK_Identity)
3620 Result = ImplicitConversionSequence::Worse;
3621 else
3622 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003623 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003624 return ImplicitConversionSequence::Indistinguishable;
3625
3626 if (SCS1.Third == SCS2.Third) {
3627 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3628 : ImplicitConversionSequence::Indistinguishable;
3629 }
3630
3631 if (SCS1.Third == ICK_Identity)
3632 return Result == ImplicitConversionSequence::Worse
3633 ? ImplicitConversionSequence::Indistinguishable
3634 : ImplicitConversionSequence::Better;
3635
3636 if (SCS2.Third == ICK_Identity)
3637 return Result == ImplicitConversionSequence::Better
3638 ? ImplicitConversionSequence::Indistinguishable
3639 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003641 return ImplicitConversionSequence::Indistinguishable;
3642}
3643
Douglas Gregore696ebb2011-01-26 14:52:12 +00003644/// \brief Determine whether one of the given reference bindings is better
3645/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003646static bool
3647isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3648 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003649 // C++0x [over.ics.rank]p3b4:
3650 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3651 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003652 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003653 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003654 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003655 // reference*.
3656 //
3657 // FIXME: Rvalue references. We're going rogue with the above edits,
3658 // because the semantics in the current C++0x working paper (N3225 at the
3659 // time of this writing) break the standard definition of std::forward
3660 // and std::reference_wrapper when dealing with references to functions.
3661 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003662 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3663 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3664 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003665
Douglas Gregore696ebb2011-01-26 14:52:12 +00003666 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3667 SCS2.IsLvalueReference) ||
3668 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003669 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003670}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003672/// CompareStandardConversionSequences - Compare two standard
3673/// conversion sequences to determine whether one is better than the
3674/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003675static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003676CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003677 const StandardConversionSequence& SCS1,
3678 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003679{
3680 // Standard conversion sequence S1 is a better conversion sequence
3681 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3682
3683 // -- S1 is a proper subsequence of S2 (comparing the conversion
3684 // sequences in the canonical form defined by 13.3.3.1.1,
3685 // excluding any Lvalue Transformation; the identity conversion
3686 // sequence is considered to be a subsequence of any
3687 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003688 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003689 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003690 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003691
3692 // -- the rank of S1 is better than the rank of S2 (by the rules
3693 // defined below), or, if not that,
3694 ImplicitConversionRank Rank1 = SCS1.getRank();
3695 ImplicitConversionRank Rank2 = SCS2.getRank();
3696 if (Rank1 < Rank2)
3697 return ImplicitConversionSequence::Better;
3698 else if (Rank2 < Rank1)
3699 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003700
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003701 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3702 // are indistinguishable unless one of the following rules
3703 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003704
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003705 // A conversion that is not a conversion of a pointer, or
3706 // pointer to member, to bool is better than another conversion
3707 // that is such a conversion.
3708 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3709 return SCS2.isPointerConversionToBool()
3710 ? ImplicitConversionSequence::Better
3711 : ImplicitConversionSequence::Worse;
3712
Douglas Gregor5c407d92008-10-23 00:40:37 +00003713 // C++ [over.ics.rank]p4b2:
3714 //
3715 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003716 // conversion of B* to A* is better than conversion of B* to
3717 // void*, and conversion of A* to void* is better than conversion
3718 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003719 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003720 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003721 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003722 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003723 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3724 // Exactly one of the conversion sequences is a conversion to
3725 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003726 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3727 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003728 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3729 // Neither conversion sequence converts to a void pointer; compare
3730 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003731 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003732 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003733 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003734 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3735 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003736 // Both conversion sequences are conversions to void
3737 // pointers. Compare the source types to determine if there's an
3738 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003739 QualType FromType1 = SCS1.getFromType();
3740 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003741
3742 // Adjust the types we're converting from via the array-to-pointer
3743 // conversion, if we need to.
3744 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003745 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003746 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003747 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003748
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003749 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3750 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003751
Richard Smith0f59cb32015-12-18 21:45:41 +00003752 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003753 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003754 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003755 return ImplicitConversionSequence::Worse;
3756
3757 // Objective-C++: If one interface is more specific than the
3758 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003759 const ObjCObjectPointerType* FromObjCPtr1
3760 = FromType1->getAs<ObjCObjectPointerType>();
3761 const ObjCObjectPointerType* FromObjCPtr2
3762 = FromType2->getAs<ObjCObjectPointerType>();
3763 if (FromObjCPtr1 && FromObjCPtr2) {
3764 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3765 FromObjCPtr2);
3766 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3767 FromObjCPtr1);
3768 if (AssignLeft != AssignRight) {
3769 return AssignLeft? ImplicitConversionSequence::Better
3770 : ImplicitConversionSequence::Worse;
3771 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003772 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003773 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003774
3775 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3776 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003777 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003778 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003779 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003780
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003781 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003782 // Check for a better reference binding based on the kind of bindings.
3783 if (isBetterReferenceBindingKind(SCS1, SCS2))
3784 return ImplicitConversionSequence::Better;
3785 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3786 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787
Sebastian Redlb28b4072009-03-22 23:49:27 +00003788 // C++ [over.ics.rank]p3b4:
3789 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3790 // which the references refer are the same type except for
3791 // top-level cv-qualifiers, and the type to which the reference
3792 // initialized by S2 refers is more cv-qualified than the type
3793 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003794 QualType T1 = SCS1.getToType(2);
3795 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003796 T1 = S.Context.getCanonicalType(T1);
3797 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003798 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003799 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3800 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003801 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003802 // Objective-C++ ARC: If the references refer to objects with different
3803 // lifetimes, prefer bindings that don't change lifetime.
3804 if (SCS1.ObjCLifetimeConversionBinding !=
3805 SCS2.ObjCLifetimeConversionBinding) {
3806 return SCS1.ObjCLifetimeConversionBinding
3807 ? ImplicitConversionSequence::Worse
3808 : ImplicitConversionSequence::Better;
3809 }
3810
Chandler Carruth8e543b32010-12-12 08:17:55 +00003811 // If the type is an array type, promote the element qualifiers to the
3812 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003813 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003814 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003815 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003816 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003817 if (T2.isMoreQualifiedThan(T1))
3818 return ImplicitConversionSequence::Better;
3819 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003820 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003821 }
3822 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003823
Francois Pichet08d2fa02011-09-18 21:37:37 +00003824 // In Microsoft mode, prefer an integral conversion to a
3825 // floating-to-integral conversion if the integral conversion
3826 // is between types of the same size.
3827 // For example:
3828 // void f(float);
3829 // void f(int);
3830 // int main {
3831 // long a;
3832 // f(a);
3833 // }
3834 // Here, MSVC will call f(int) instead of generating a compile error
3835 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003836 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3837 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003838 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003839 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003840 return ImplicitConversionSequence::Better;
3841
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003842 return ImplicitConversionSequence::Indistinguishable;
3843}
3844
3845/// CompareQualificationConversions - Compares two standard conversion
3846/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003847/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003848static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003849CompareQualificationConversions(Sema &S,
3850 const StandardConversionSequence& SCS1,
3851 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003852 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003853 // -- S1 and S2 differ only in their qualification conversion and
3854 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3855 // cv-qualification signature of type T1 is a proper subset of
3856 // the cv-qualification signature of type T2, and S1 is not the
3857 // deprecated string literal array-to-pointer conversion (4.2).
3858 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3859 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3860 return ImplicitConversionSequence::Indistinguishable;
3861
3862 // FIXME: the example in the standard doesn't use a qualification
3863 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003864 QualType T1 = SCS1.getToType(2);
3865 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003866 T1 = S.Context.getCanonicalType(T1);
3867 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003868 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003869 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3870 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003871
3872 // If the types are the same, we won't learn anything by unwrapped
3873 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003874 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003875 return ImplicitConversionSequence::Indistinguishable;
3876
Chandler Carruth607f38e2009-12-29 07:16:59 +00003877 // If the type is an array type, promote the element qualifiers to the type
3878 // for comparison.
3879 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003880 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003881 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003882 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003883
Mike Stump11289f42009-09-09 15:08:12 +00003884 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003885 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003886
3887 // Objective-C++ ARC:
3888 // Prefer qualification conversions not involving a change in lifetime
3889 // to qualification conversions that do not change lifetime.
3890 if (SCS1.QualificationIncludesObjCLifetime !=
3891 SCS2.QualificationIncludesObjCLifetime) {
3892 Result = SCS1.QualificationIncludesObjCLifetime
3893 ? ImplicitConversionSequence::Worse
3894 : ImplicitConversionSequence::Better;
3895 }
3896
John McCall5c32be02010-08-24 20:38:10 +00003897 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003898 // Within each iteration of the loop, we check the qualifiers to
3899 // determine if this still looks like a qualification
3900 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003901 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003902 // until there are no more pointers or pointers-to-members left
3903 // to unwrap. This essentially mimics what
3904 // IsQualificationConversion does, but here we're checking for a
3905 // strict subset of qualifiers.
3906 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3907 // The qualifiers are the same, so this doesn't tell us anything
3908 // about how the sequences rank.
3909 ;
3910 else if (T2.isMoreQualifiedThan(T1)) {
3911 // T1 has fewer qualifiers, so it could be the better sequence.
3912 if (Result == ImplicitConversionSequence::Worse)
3913 // Neither has qualifiers that are a subset of the other's
3914 // qualifiers.
3915 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003916
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003917 Result = ImplicitConversionSequence::Better;
3918 } else if (T1.isMoreQualifiedThan(T2)) {
3919 // T2 has fewer qualifiers, so it could be the better sequence.
3920 if (Result == ImplicitConversionSequence::Better)
3921 // Neither has qualifiers that are a subset of the other's
3922 // qualifiers.
3923 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003924
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003925 Result = ImplicitConversionSequence::Worse;
3926 } else {
3927 // Qualifiers are disjoint.
3928 return ImplicitConversionSequence::Indistinguishable;
3929 }
3930
3931 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003932 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003933 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003934 }
3935
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003936 // Check that the winning standard conversion sequence isn't using
3937 // the deprecated string literal array to pointer conversion.
3938 switch (Result) {
3939 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003940 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003941 Result = ImplicitConversionSequence::Indistinguishable;
3942 break;
3943
3944 case ImplicitConversionSequence::Indistinguishable:
3945 break;
3946
3947 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003948 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003949 Result = ImplicitConversionSequence::Indistinguishable;
3950 break;
3951 }
3952
3953 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003954}
3955
Douglas Gregor5c407d92008-10-23 00:40:37 +00003956/// CompareDerivedToBaseConversions - Compares two standard conversion
3957/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003958/// various kinds of derived-to-base conversions (C++
3959/// [over.ics.rank]p4b3). As part of these checks, we also look at
3960/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003961static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003962CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003963 const StandardConversionSequence& SCS1,
3964 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003965 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003966 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003967 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003968 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003969
3970 // Adjust the types we're converting from via the array-to-pointer
3971 // conversion, if we need to.
3972 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003973 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003974 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003975 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003976
3977 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003978 FromType1 = S.Context.getCanonicalType(FromType1);
3979 ToType1 = S.Context.getCanonicalType(ToType1);
3980 FromType2 = S.Context.getCanonicalType(FromType2);
3981 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003982
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003983 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003984 //
3985 // If class B is derived directly or indirectly from class A and
3986 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003987 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003988 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003989 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003990 SCS2.Second == ICK_Pointer_Conversion &&
3991 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3992 FromType1->isPointerType() && FromType2->isPointerType() &&
3993 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003994 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003995 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003996 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003997 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003998 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003999 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004000 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004001 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004002
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004003 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004004 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004005 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004006 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004007 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004008 return ImplicitConversionSequence::Worse;
4009 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004010
4011 // -- conversion of B* to A* is better than conversion of C* to A*,
4012 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004013 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004014 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004015 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004016 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004017 }
4018 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4019 SCS2.Second == ICK_Pointer_Conversion) {
4020 const ObjCObjectPointerType *FromPtr1
4021 = FromType1->getAs<ObjCObjectPointerType>();
4022 const ObjCObjectPointerType *FromPtr2
4023 = FromType2->getAs<ObjCObjectPointerType>();
4024 const ObjCObjectPointerType *ToPtr1
4025 = ToType1->getAs<ObjCObjectPointerType>();
4026 const ObjCObjectPointerType *ToPtr2
4027 = ToType2->getAs<ObjCObjectPointerType>();
4028
4029 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4030 // Apply the same conversion ranking rules for Objective-C pointer types
4031 // that we do for C++ pointers to class types. However, we employ the
4032 // Objective-C pseudo-subtyping relationship used for assignment of
4033 // Objective-C pointer types.
4034 bool FromAssignLeft
4035 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4036 bool FromAssignRight
4037 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4038 bool ToAssignLeft
4039 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4040 bool ToAssignRight
4041 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4042
4043 // A conversion to an a non-id object pointer type or qualified 'id'
4044 // type is better than a conversion to 'id'.
4045 if (ToPtr1->isObjCIdType() &&
4046 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4047 return ImplicitConversionSequence::Worse;
4048 if (ToPtr2->isObjCIdType() &&
4049 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4050 return ImplicitConversionSequence::Better;
4051
4052 // A conversion to a non-id object pointer type is better than a
4053 // conversion to a qualified 'id' type
4054 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4055 return ImplicitConversionSequence::Worse;
4056 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4057 return ImplicitConversionSequence::Better;
4058
4059 // A conversion to an a non-Class object pointer type or qualified 'Class'
4060 // type is better than a conversion to 'Class'.
4061 if (ToPtr1->isObjCClassType() &&
4062 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4063 return ImplicitConversionSequence::Worse;
4064 if (ToPtr2->isObjCClassType() &&
4065 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4066 return ImplicitConversionSequence::Better;
4067
4068 // A conversion to a non-Class object pointer type is better than a
4069 // conversion to a qualified 'Class' type.
4070 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4071 return ImplicitConversionSequence::Worse;
4072 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4073 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004074
Douglas Gregor058d3de2011-01-31 18:51:41 +00004075 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4076 if (S.Context.hasSameType(FromType1, FromType2) &&
4077 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4078 (ToAssignLeft != ToAssignRight))
4079 return ToAssignLeft? ImplicitConversionSequence::Worse
4080 : ImplicitConversionSequence::Better;
4081
4082 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4083 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4084 (FromAssignLeft != FromAssignRight))
4085 return FromAssignLeft? ImplicitConversionSequence::Better
4086 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004087 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004088 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004089
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004090 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004091 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4092 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4093 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004094 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004095 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004096 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004097 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004098 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004099 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004100 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004101 ToType2->getAs<MemberPointerType>();
4102 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4103 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4104 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4105 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4106 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4107 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4108 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4109 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004110 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004111 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004112 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004113 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004114 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004115 return ImplicitConversionSequence::Better;
4116 }
4117 // conversion of B::* to C::* is better than conversion of A::* to C::*
4118 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004119 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004120 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004121 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004122 return ImplicitConversionSequence::Worse;
4123 }
4124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004125
Douglas Gregor5ab11652010-04-17 22:01:05 +00004126 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004127 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004128 // -- binding of an expression of type C to a reference of type
4129 // B& is better than binding an expression of type C to a
4130 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004131 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4132 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004133 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004134 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004135 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004136 return ImplicitConversionSequence::Worse;
4137 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004138
Douglas Gregor2fe98832008-11-03 19:09:14 +00004139 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004140 // -- binding of an expression of type B to a reference of type
4141 // A& is better than binding an expression of type C to a
4142 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004143 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4144 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004145 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004146 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004147 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004148 return ImplicitConversionSequence::Worse;
4149 }
4150 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004151
Douglas Gregor5c407d92008-10-23 00:40:37 +00004152 return ImplicitConversionSequence::Indistinguishable;
4153}
4154
Douglas Gregor45bb4832013-03-26 23:36:30 +00004155/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4156/// C++ class.
4157static bool isTypeValid(QualType T) {
4158 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4159 return !Record->isInvalidDecl();
4160
4161 return true;
4162}
4163
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004164/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4165/// determine whether they are reference-related,
4166/// reference-compatible, reference-compatible with added
4167/// qualification, or incompatible, for use in C++ initialization by
4168/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4169/// type, and the first type (T1) is the pointee type of the reference
4170/// type being initialized.
4171Sema::ReferenceCompareResult
4172Sema::CompareReferenceRelationship(SourceLocation Loc,
4173 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004174 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004175 bool &ObjCConversion,
4176 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004177 assert(!OrigT1->isReferenceType() &&
4178 "T1 must be the pointee type of the reference type");
4179 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4180
4181 QualType T1 = Context.getCanonicalType(OrigT1);
4182 QualType T2 = Context.getCanonicalType(OrigT2);
4183 Qualifiers T1Quals, T2Quals;
4184 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4185 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4186
4187 // C++ [dcl.init.ref]p4:
4188 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4189 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4190 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004191 DerivedToBase = false;
4192 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004193 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004194 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004195 if (UnqualT1 == UnqualT2) {
4196 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004197 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004198 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004199 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004200 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004201 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4202 UnqualT2->isObjCObjectOrInterfaceType() &&
4203 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4204 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004205 else if (UnqualT2->isFunctionType() &&
4206 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4207 // C++1z [dcl.init.ref]p4:
4208 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4209 // function" and T1 is "function"
4210 //
4211 // We extend this to also apply to 'noreturn', so allow any function
4212 // conversion between function types.
4213 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004214 else
4215 return Ref_Incompatible;
4216
4217 // At this point, we know that T1 and T2 are reference-related (at
4218 // least).
4219
4220 // If the type is an array type, promote the element qualifiers to the type
4221 // for comparison.
4222 if (isa<ArrayType>(T1) && T1Quals)
4223 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4224 if (isa<ArrayType>(T2) && T2Quals)
4225 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4226
4227 // C++ [dcl.init.ref]p4:
4228 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4229 // reference-related to T2 and cv1 is the same cv-qualification
4230 // as, or greater cv-qualification than, cv2. For purposes of
4231 // overload resolution, cases for which cv1 is greater
4232 // cv-qualification than cv2 are identified as
4233 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004234 //
4235 // Note that we also require equivalence of Objective-C GC and address-space
4236 // qualifiers when performing these computations, so that e.g., an int in
4237 // address space 1 is not reference-compatible with an int in address
4238 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004239 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4240 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004241 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4242 ObjCLifetimeConversion = true;
4243
John McCall31168b02011-06-15 23:02:42 +00004244 T1Quals.removeObjCLifetime();
4245 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004246 }
4247
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004248 // MS compiler ignores __unaligned qualifier for references; do the same.
4249 T1Quals.removeUnaligned();
4250 T2Quals.removeUnaligned();
4251
Richard Smithce766292016-10-21 23:01:55 +00004252 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004253 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004254 else
4255 return Ref_Related;
4256}
4257
Douglas Gregor836a7e82010-08-11 02:15:33 +00004258/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004259/// with DeclType. Return true if something definite is found.
4260static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004261FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4262 QualType DeclType, SourceLocation DeclLoc,
4263 Expr *Init, QualType T2, bool AllowRvalues,
4264 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004265 assert(T2->isRecordType() && "Can only find conversions of record types.");
4266 CXXRecordDecl *T2RecordDecl
4267 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4268
Richard Smith100b24a2014-04-17 01:52:14 +00004269 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004270 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4271 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004272 NamedDecl *D = *I;
4273 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4274 if (isa<UsingShadowDecl>(D))
4275 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4276
4277 FunctionTemplateDecl *ConvTemplate
4278 = dyn_cast<FunctionTemplateDecl>(D);
4279 CXXConversionDecl *Conv;
4280 if (ConvTemplate)
4281 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4282 else
4283 Conv = cast<CXXConversionDecl>(D);
4284
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004286 // explicit conversions, skip it.
4287 if (!AllowExplicit && Conv->isExplicit())
4288 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004289
Douglas Gregor836a7e82010-08-11 02:15:33 +00004290 if (AllowRvalues) {
4291 bool DerivedToBase = false;
4292 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004293 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004294
4295 // If we are initializing an rvalue reference, don't permit conversion
4296 // functions that return lvalues.
4297 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4298 const ReferenceType *RefType
4299 = Conv->getConversionType()->getAs<LValueReferenceType>();
4300 if (RefType && !RefType->getPointeeType()->isFunctionType())
4301 continue;
4302 }
4303
Douglas Gregor836a7e82010-08-11 02:15:33 +00004304 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004305 S.CompareReferenceRelationship(
4306 DeclLoc,
4307 Conv->getConversionType().getNonReferenceType()
4308 .getUnqualifiedType(),
4309 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004310 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004311 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004312 continue;
4313 } else {
4314 // If the conversion function doesn't return a reference type,
4315 // it can't be considered for this conversion. An rvalue reference
4316 // is only acceptable if its referencee is a function type.
4317
4318 const ReferenceType *RefType =
4319 Conv->getConversionType()->getAs<ReferenceType>();
4320 if (!RefType ||
4321 (!RefType->isLValueReferenceType() &&
4322 !RefType->getPointeeType()->isFunctionType()))
4323 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004324 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004325
Douglas Gregor836a7e82010-08-11 02:15:33 +00004326 if (ConvTemplate)
4327 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004328 Init, DeclType, CandidateSet,
4329 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004330 else
4331 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004332 DeclType, CandidateSet,
4333 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004334 }
4335
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004336 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4337
Sebastian Redld92badf2010-06-30 18:13:39 +00004338 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004339 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004340 case OR_Success:
4341 // C++ [over.ics.ref]p1:
4342 //
4343 // [...] If the parameter binds directly to the result of
4344 // applying a conversion function to the argument
4345 // expression, the implicit conversion sequence is a
4346 // user-defined conversion sequence (13.3.3.1.2), with the
4347 // second standard conversion sequence either an identity
4348 // conversion or, if the conversion function returns an
4349 // entity of a type that is a derived class of the parameter
4350 // type, a derived-to-base Conversion.
4351 if (!Best->FinalConversion.DirectBinding)
4352 return false;
4353
4354 ICS.setUserDefined();
4355 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4356 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004357 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004358 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004359 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004360 ICS.UserDefined.EllipsisConversion = false;
4361 assert(ICS.UserDefined.After.ReferenceBinding &&
4362 ICS.UserDefined.After.DirectBinding &&
4363 "Expected a direct reference binding!");
4364 return true;
4365
4366 case OR_Ambiguous:
4367 ICS.setAmbiguous();
4368 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4369 Cand != CandidateSet.end(); ++Cand)
4370 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004371 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004372 return true;
4373
4374 case OR_No_Viable_Function:
4375 case OR_Deleted:
4376 // There was no suitable conversion, or we found a deleted
4377 // conversion; continue with other checks.
4378 return false;
4379 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004380
David Blaikie8a40f702012-01-17 06:56:22 +00004381 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004382}
4383
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004384/// \brief Compute an implicit conversion sequence for reference
4385/// initialization.
4386static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004387TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004388 SourceLocation DeclLoc,
4389 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004390 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004391 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4392
4393 // Most paths end in a failed conversion.
4394 ImplicitConversionSequence ICS;
4395 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4396
4397 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4398 QualType T2 = Init->getType();
4399
4400 // If the initializer is the address of an overloaded function, try
4401 // to resolve the overloaded function. If all goes well, T2 is the
4402 // type of the resulting function.
4403 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4404 DeclAccessPair Found;
4405 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4406 false, Found))
4407 T2 = Fn->getType();
4408 }
4409
4410 // Compute some basic properties of the types and the initializer.
4411 bool isRValRef = DeclType->isRValueReferenceType();
4412 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004413 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004414 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004415 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004416 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004417 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004418 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004419
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004420
Sebastian Redld92badf2010-06-30 18:13:39 +00004421 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004422 // A reference to type "cv1 T1" is initialized by an expression
4423 // of type "cv2 T2" as follows:
4424
Sebastian Redld92badf2010-06-30 18:13:39 +00004425 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004426 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004427 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4428 // reference-compatible with "cv2 T2," or
4429 //
4430 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004431 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004432 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004433 // When a parameter of reference type binds directly (8.5.3)
4434 // to an argument expression, the implicit conversion sequence
4435 // is the identity conversion, unless the argument expression
4436 // has a type that is a derived class of the parameter type,
4437 // in which case the implicit conversion sequence is a
4438 // derived-to-base Conversion (13.3.3.1).
4439 ICS.setStandard();
4440 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004441 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4442 : ObjCConversion? ICK_Compatible_Conversion
4443 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004444 ICS.Standard.Third = ICK_Identity;
4445 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4446 ICS.Standard.setToType(0, T2);
4447 ICS.Standard.setToType(1, T1);
4448 ICS.Standard.setToType(2, T1);
4449 ICS.Standard.ReferenceBinding = true;
4450 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004451 ICS.Standard.IsLvalueReference = !isRValRef;
4452 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4453 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004454 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004455 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004456 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004457 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004458
Sebastian Redld92badf2010-06-30 18:13:39 +00004459 // Nothing more to do: the inaccessibility/ambiguity check for
4460 // derived-to-base conversions is suppressed when we're
4461 // computing the implicit conversion sequence (C++
4462 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004463 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004464 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004465
Sebastian Redld92badf2010-06-30 18:13:39 +00004466 // -- has a class type (i.e., T2 is a class type), where T1 is
4467 // not reference-related to T2, and can be implicitly
4468 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4469 // is reference-compatible with "cv3 T3" 92) (this
4470 // conversion is selected by enumerating the applicable
4471 // conversion functions (13.3.1.6) and choosing the best
4472 // one through overload resolution (13.3)),
4473 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004474 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004475 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004476 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4477 Init, T2, /*AllowRvalues=*/false,
4478 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004479 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004480 }
4481 }
4482
Sebastian Redld92badf2010-06-30 18:13:39 +00004483 // -- Otherwise, the reference shall be an lvalue reference to a
4484 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004485 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004486 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004487 return ICS;
4488
Douglas Gregorf143cd52011-01-24 16:14:37 +00004489 // -- If the initializer expression
4490 //
4491 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004492 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004493 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004494 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004495 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4496 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004497 ICS.setStandard();
4498 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004499 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004500 : ObjCConversion? ICK_Compatible_Conversion
4501 : ICK_Identity;
4502 ICS.Standard.Third = ICK_Identity;
4503 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4504 ICS.Standard.setToType(0, T2);
4505 ICS.Standard.setToType(1, T1);
4506 ICS.Standard.setToType(2, T1);
4507 ICS.Standard.ReferenceBinding = true;
4508 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4509 // binding unless we're binding to a class prvalue.
4510 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4511 // allow the use of rvalue references in C++98/03 for the benefit of
4512 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004513 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004514 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004515 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004516 ICS.Standard.IsLvalueReference = !isRValRef;
4517 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004519 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004520 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004521 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004522 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004523 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525
Douglas Gregorf143cd52011-01-24 16:14:37 +00004526 // -- has a class type (i.e., T2 is a class type), where T1 is not
4527 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004528 // an xvalue, class prvalue, or function lvalue of type
4529 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004530 // "cv3 T3",
4531 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004532 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004533 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004534 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004535 // class subobject).
4536 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004537 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004538 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4539 Init, T2, /*AllowRvalues=*/true,
4540 AllowExplicit)) {
4541 // In the second case, if the reference is an rvalue reference
4542 // and the second standard conversion sequence of the
4543 // user-defined conversion sequence includes an lvalue-to-rvalue
4544 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004546 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4547 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4548
Douglas Gregor95273c32011-01-21 16:36:05 +00004549 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004550 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004551
Richard Smith19172c42014-07-14 02:28:44 +00004552 // A temporary of function type cannot be created; don't even try.
4553 if (T1->isFunctionType())
4554 return ICS;
4555
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004556 // -- Otherwise, a temporary of type "cv1 T1" is created and
4557 // initialized from the initializer expression using the
4558 // rules for a non-reference copy initialization (8.5). The
4559 // reference is then bound to the temporary. If T1 is
4560 // reference-related to T2, cv1 must be the same
4561 // cv-qualification as, or greater cv-qualification than,
4562 // cv2; otherwise, the program is ill-formed.
4563 if (RefRelationship == Sema::Ref_Related) {
4564 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4565 // we would be reference-compatible or reference-compatible with
4566 // added qualification. But that wasn't the case, so the reference
4567 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004568 //
4569 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004570 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004571 Qualifiers T1Quals = T1.getQualifiers();
4572 Qualifiers T2Quals = T2.getQualifiers();
4573 T1Quals.removeObjCGCAttr();
4574 T1Quals.removeObjCLifetime();
4575 T2Quals.removeObjCGCAttr();
4576 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004577 // MS compiler ignores __unaligned qualifier for references; do the same.
4578 T1Quals.removeUnaligned();
4579 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004580 if (!T1Quals.compatiblyIncludes(T2Quals))
4581 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004582 }
4583
4584 // If at least one of the types is a class type, the types are not
4585 // related, and we aren't allowed any user conversions, the
4586 // reference binding fails. This case is important for breaking
4587 // recursion, since TryImplicitConversion below will attempt to
4588 // create a temporary through the use of a copy constructor.
4589 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4590 (T1->isRecordType() || T2->isRecordType()))
4591 return ICS;
4592
Douglas Gregorcba72b12011-01-21 05:18:22 +00004593 // If T1 is reference-related to T2 and the reference is an rvalue
4594 // reference, the initializer expression shall not be an lvalue.
4595 if (RefRelationship >= Sema::Ref_Related &&
4596 isRValRef && Init->Classify(S.Context).isLValue())
4597 return ICS;
4598
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004599 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004600 // When a parameter of reference type is not bound directly to
4601 // an argument expression, the conversion sequence is the one
4602 // required to convert the argument expression to the
4603 // underlying type of the reference according to
4604 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4605 // to copy-initializing a temporary of the underlying type with
4606 // the argument expression. Any difference in top-level
4607 // cv-qualification is subsumed by the initialization itself
4608 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004609 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4610 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004611 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004612 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004613 /*AllowObjCWritebackConversion=*/false,
4614 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004615
4616 // Of course, that's still a reference binding.
4617 if (ICS.isStandard()) {
4618 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004619 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004620 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004621 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004622 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004623 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004624 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004625 const ReferenceType *LValRefType =
4626 ICS.UserDefined.ConversionFunction->getReturnType()
4627 ->getAs<LValueReferenceType>();
4628
4629 // C++ [over.ics.ref]p3:
4630 // Except for an implicit object parameter, for which see 13.3.1, a
4631 // standard conversion sequence cannot be formed if it requires [...]
4632 // binding an rvalue reference to an lvalue other than a function
4633 // lvalue.
4634 // Note that the function case is not possible here.
4635 if (DeclType->isRValueReferenceType() && LValRefType) {
4636 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4637 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4638 // reference to an rvalue!
4639 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4640 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004641 }
Richard Smith19172c42014-07-14 02:28:44 +00004642
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004643 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004644 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004645 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4646 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004647 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4648 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004649 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004650
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004651 return ICS;
4652}
4653
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004654static ImplicitConversionSequence
4655TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4656 bool SuppressUserConversions,
4657 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004658 bool AllowObjCWritebackConversion,
4659 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004660
4661/// TryListConversion - Try to copy-initialize a value of type ToType from the
4662/// initializer list From.
4663static ImplicitConversionSequence
4664TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4665 bool SuppressUserConversions,
4666 bool InOverloadResolution,
4667 bool AllowObjCWritebackConversion) {
4668 // C++11 [over.ics.list]p1:
4669 // When an argument is an initializer list, it is not an expression and
4670 // special rules apply for converting it to a parameter type.
4671
4672 ImplicitConversionSequence Result;
4673 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4674
Sebastian Redl09edce02012-01-23 22:09:39 +00004675 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004676 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004677 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004678 return Result;
4679
Larisse Voufo19d08672015-01-27 18:47:05 +00004680 // Per DR1467:
4681 // If the parameter type is a class X and the initializer list has a single
4682 // element of type cv U, where U is X or a class derived from X, the
4683 // implicit conversion sequence is the one required to convert the element
4684 // to the parameter type.
4685 //
4686 // Otherwise, if the parameter type is a character array [... ]
4687 // and the initializer list has a single element that is an
4688 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4689 // implicit conversion sequence is the identity conversion.
4690 if (From->getNumInits() == 1) {
4691 if (ToType->isRecordType()) {
4692 QualType InitType = From->getInit(0)->getType();
4693 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004694 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004695 return TryCopyInitialization(S, From->getInit(0), ToType,
4696 SuppressUserConversions,
4697 InOverloadResolution,
4698 AllowObjCWritebackConversion);
4699 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004700 // FIXME: Check the other conditions here: array of character type,
4701 // initializer is a string literal.
4702 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004703 InitializedEntity Entity =
4704 InitializedEntity::InitializeParameter(S.Context, ToType,
4705 /*Consumed=*/false);
4706 if (S.CanPerformCopyInitialization(Entity, From)) {
4707 Result.setStandard();
4708 Result.Standard.setAsIdentityConversion();
4709 Result.Standard.setFromType(ToType);
4710 Result.Standard.setAllToTypes(ToType);
4711 return Result;
4712 }
4713 }
4714 }
4715
4716 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004717 // C++11 [over.ics.list]p2:
4718 // If the parameter type is std::initializer_list<X> or "array of X" and
4719 // all the elements can be implicitly converted to X, the implicit
4720 // conversion sequence is the worst conversion necessary to convert an
4721 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004722 //
4723 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004724 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004725 // list has exactly N elements or if it has fewer than N elements and X is
4726 // default-constructible, and if all the elements of the initializer list
4727 // can be implicitly converted to X, the implicit conversion sequence is
4728 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004729 //
4730 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004731 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004732 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004733 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004734 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004735 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004736 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004737 if (!X.isNull()) {
4738 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4739 Expr *Init = From->getInit(i);
4740 ImplicitConversionSequence ICS =
4741 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4742 InOverloadResolution,
4743 AllowObjCWritebackConversion);
4744 // If a single element isn't convertible, fail.
4745 if (ICS.isBad()) {
4746 Result = ICS;
4747 break;
4748 }
4749 // Otherwise, look for the worst conversion.
4750 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004751 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4752 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004753 ImplicitConversionSequence::Worse)
4754 Result = ICS;
4755 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004756
4757 // For an empty list, we won't have computed any conversion sequence.
4758 // Introduce the identity conversion sequence.
4759 if (From->getNumInits() == 0) {
4760 Result.setStandard();
4761 Result.Standard.setAsIdentityConversion();
4762 Result.Standard.setFromType(ToType);
4763 Result.Standard.setAllToTypes(ToType);
4764 }
4765
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004766 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004767 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004768 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004769
Larisse Voufo19d08672015-01-27 18:47:05 +00004770 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004771 // C++11 [over.ics.list]p3:
4772 // Otherwise, if the parameter is a non-aggregate class X and overload
4773 // resolution chooses a single best constructor [...] the implicit
4774 // conversion sequence is a user-defined conversion sequence. If multiple
4775 // constructors are viable but none is better than the others, the
4776 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004777 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4778 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004779 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4780 /*AllowExplicit=*/false,
4781 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004782 AllowObjCWritebackConversion,
4783 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004784 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004785
Larisse Voufo19d08672015-01-27 18:47:05 +00004786 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004787 // C++11 [over.ics.list]p4:
4788 // Otherwise, if the parameter has an aggregate type which can be
4789 // initialized from the initializer list [...] the implicit conversion
4790 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004791 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004792 // Type is an aggregate, argument is an init list. At this point it comes
4793 // down to checking whether the initialization works.
4794 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004795 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4796 // need to call into the initialization code here; overload resolution
4797 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004798 InitializedEntity Entity =
4799 InitializedEntity::InitializeParameter(S.Context, ToType,
4800 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004801 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004802 Result.setUserDefined();
4803 Result.UserDefined.Before.setAsIdentityConversion();
4804 // Initializer lists don't have a type.
4805 Result.UserDefined.Before.setFromType(QualType());
4806 Result.UserDefined.Before.setAllToTypes(QualType());
4807
4808 Result.UserDefined.After.setAsIdentityConversion();
4809 Result.UserDefined.After.setFromType(ToType);
4810 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004811 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004812 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004813 return Result;
4814 }
4815
Larisse Voufo19d08672015-01-27 18:47:05 +00004816 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004817 // C++11 [over.ics.list]p5:
4818 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004819 if (ToType->isReferenceType()) {
4820 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4821 // mention initializer lists in any way. So we go by what list-
4822 // initialization would do and try to extrapolate from that.
4823
4824 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4825
4826 // If the initializer list has a single element that is reference-related
4827 // to the parameter type, we initialize the reference from that.
4828 if (From->getNumInits() == 1) {
4829 Expr *Init = From->getInit(0);
4830
4831 QualType T2 = Init->getType();
4832
4833 // If the initializer is the address of an overloaded function, try
4834 // to resolve the overloaded function. If all goes well, T2 is the
4835 // type of the resulting function.
4836 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4837 DeclAccessPair Found;
4838 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4839 Init, ToType, false, Found))
4840 T2 = Fn->getType();
4841 }
4842
4843 // Compute some basic properties of the types and the initializer.
4844 bool dummy1 = false;
4845 bool dummy2 = false;
4846 bool dummy3 = false;
4847 Sema::ReferenceCompareResult RefRelationship
4848 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4849 dummy2, dummy3);
4850
Richard Smith4d2bbd72013-09-06 01:22:42 +00004851 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004852 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4853 SuppressUserConversions,
4854 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004855 }
Sebastian Redldf888642011-12-03 14:54:30 +00004856 }
4857
4858 // Otherwise, we bind the reference to a temporary created from the
4859 // initializer list.
4860 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4861 InOverloadResolution,
4862 AllowObjCWritebackConversion);
4863 if (Result.isFailure())
4864 return Result;
4865 assert(!Result.isEllipsis() &&
4866 "Sub-initialization cannot result in ellipsis conversion.");
4867
4868 // Can we even bind to a temporary?
4869 if (ToType->isRValueReferenceType() ||
4870 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4871 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4872 Result.UserDefined.After;
4873 SCS.ReferenceBinding = true;
4874 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4875 SCS.BindsToRvalue = true;
4876 SCS.BindsToFunctionLvalue = false;
4877 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4878 SCS.ObjCLifetimeConversionBinding = false;
4879 } else
4880 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4881 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004882 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004883 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004884
Larisse Voufo19d08672015-01-27 18:47:05 +00004885 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004886 // C++11 [over.ics.list]p6:
4887 // Otherwise, if the parameter type is not a class:
4888 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004889 // - if the initializer list has one element that is not itself an
4890 // initializer list, the implicit conversion sequence is the one
4891 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004892 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004893 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004894 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4895 SuppressUserConversions,
4896 InOverloadResolution,
4897 AllowObjCWritebackConversion);
4898 // - if the initializer list has no elements, the implicit conversion
4899 // sequence is the identity conversion.
4900 else if (NumInits == 0) {
4901 Result.setStandard();
4902 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004903 Result.Standard.setFromType(ToType);
4904 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004905 }
4906 return Result;
4907 }
4908
Larisse Voufo19d08672015-01-27 18:47:05 +00004909 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004910 // C++11 [over.ics.list]p7:
4911 // In all cases other than those enumerated above, no conversion is possible
4912 return Result;
4913}
4914
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004915/// TryCopyInitialization - Try to copy-initialize a value of type
4916/// ToType from the expression From. Return the implicit conversion
4917/// sequence required to pass this argument, which may be a bad
4918/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004919/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004920/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004921static ImplicitConversionSequence
4922TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004923 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004924 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004925 bool AllowObjCWritebackConversion,
4926 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004927 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4928 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4929 InOverloadResolution,AllowObjCWritebackConversion);
4930
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004931 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004932 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004933 /*FIXME:*/From->getLocStart(),
4934 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004935 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004936
John McCall5c32be02010-08-24 20:38:10 +00004937 return TryImplicitConversion(S, From, ToType,
4938 SuppressUserConversions,
4939 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004940 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004941 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004942 AllowObjCWritebackConversion,
4943 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004944}
4945
Anna Zaks1b068122011-07-28 19:46:48 +00004946static bool TryCopyInitialization(const CanQualType FromQTy,
4947 const CanQualType ToQTy,
4948 Sema &S,
4949 SourceLocation Loc,
4950 ExprValueKind FromVK) {
4951 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4952 ImplicitConversionSequence ICS =
4953 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4954
4955 return !ICS.isBad();
4956}
4957
Douglas Gregor436424c2008-11-18 23:14:02 +00004958/// TryObjectArgumentInitialization - Try to initialize the object
4959/// parameter of the given member function (@c Method) from the
4960/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004961static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004962TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004963 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004964 CXXMethodDecl *Method,
4965 CXXRecordDecl *ActingContext) {
4966 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004967 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4968 // const volatile object.
4969 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4970 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004971 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004972
4973 // Set up the conversion sequence as a "bad" conversion, to allow us
4974 // to exit early.
4975 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004976
4977 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004978 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004979 FromType = PT->getPointeeType();
4980
Douglas Gregor02824322011-01-26 19:30:28 +00004981 // When we had a pointer, it's implicitly dereferenced, so we
4982 // better have an lvalue.
4983 assert(FromClassification.isLValue());
4984 }
4985
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004986 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004987
Douglas Gregor02824322011-01-26 19:30:28 +00004988 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004989 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004990 // parameter is
4991 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004992 // - "lvalue reference to cv X" for functions declared without a
4993 // ref-qualifier or with the & ref-qualifier
4994 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004995 // ref-qualifier
4996 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004997 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004998 // cv-qualification on the member function declaration.
4999 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005000 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005001 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005002 // (C++ [over.match.funcs]p5). We perform a simplified version of
5003 // reference binding here, that allows class rvalues to bind to
5004 // non-constant references.
5005
Douglas Gregor02824322011-01-26 19:30:28 +00005006 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005007 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005008 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005009 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005010 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005011 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005012 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005013 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005014 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005015
5016 // Check that we have either the same type or a derived type. It
5017 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005018 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005019 ImplicitConversionKind SecondKind;
5020 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5021 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005022 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005023 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005024 else {
John McCall65eb8792010-02-25 01:37:24 +00005025 ICS.setBad(BadConversionSequence::unrelated_class,
5026 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005027 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005028 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005029
Douglas Gregor02824322011-01-26 19:30:28 +00005030 // Check the ref-qualifier.
5031 switch (Method->getRefQualifier()) {
5032 case RQ_None:
5033 // Do nothing; we don't care about lvalueness or rvalueness.
5034 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005035
Douglas Gregor02824322011-01-26 19:30:28 +00005036 case RQ_LValue:
5037 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5038 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005039 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005040 ImplicitParamType);
5041 return ICS;
5042 }
5043 break;
5044
5045 case RQ_RValue:
5046 if (!FromClassification.isRValue()) {
5047 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005048 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005049 ImplicitParamType);
5050 return ICS;
5051 }
5052 break;
5053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005054
Douglas Gregor436424c2008-11-18 23:14:02 +00005055 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005056 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005057 ICS.Standard.setAsIdentityConversion();
5058 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005059 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005060 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005061 ICS.Standard.ReferenceBinding = true;
5062 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005063 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005064 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005065 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5066 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5067 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005068 return ICS;
5069}
5070
5071/// PerformObjectArgumentInitialization - Perform initialization of
5072/// the implicit object parameter for the given Method with the given
5073/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005074ExprResult
5075Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005077 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005078 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005079 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005080 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005081 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005082
Douglas Gregor02824322011-01-26 19:30:28 +00005083 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005084 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005085 FromRecordType = PT->getPointeeType();
5086 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005087 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005088 } else {
5089 FromRecordType = From->getType();
5090 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005091 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005092 }
5093
John McCall6e9f8f62009-12-03 04:06:58 +00005094 // Note that we always use the true parent context when performing
5095 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005096 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005097 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5098 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005099 if (ICS.isBad()) {
5100 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5101 Qualifiers FromQs = FromRecordType.getQualifiers();
5102 Qualifiers ToQs = DestType.getQualifiers();
5103 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5104 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005105 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005106 diag::err_member_function_call_bad_cvr)
5107 << Method->getDeclName() << FromRecordType << (CVR - 1)
5108 << From->getSourceRange();
5109 Diag(Method->getLocation(), diag::note_previous_decl)
5110 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005111 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005112 }
5113 }
5114
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005115 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005116 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005117 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005118 }
Mike Stump11289f42009-09-09 15:08:12 +00005119
John Wiegley01296292011-04-08 18:41:53 +00005120 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5121 ExprResult FromRes =
5122 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5123 if (FromRes.isInvalid())
5124 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005125 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005126 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005127
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005128 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005129 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005130 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005131 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005132}
5133
Douglas Gregor5fb53972009-01-14 15:45:31 +00005134/// TryContextuallyConvertToBool - Attempt to contextually convert the
5135/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005136static ImplicitConversionSequence
5137TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005138 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005139 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005140 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005141 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005142 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005143 /*AllowObjCWritebackConversion=*/false,
5144 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005145}
5146
5147/// PerformContextuallyConvertToBool - Perform a contextual conversion
5148/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005149ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005150 if (checkPlaceholderForOverload(*this, From))
5151 return ExprError();
5152
John McCall5c32be02010-08-24 20:38:10 +00005153 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005154 if (!ICS.isBad())
5155 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005156
Fariborz Jahanian76197412009-11-18 18:26:29 +00005157 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005158 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005159 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005160 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005161 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005162}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005163
Richard Smithf8379a02012-01-18 23:55:52 +00005164/// Check that the specified conversion is permitted in a converted constant
5165/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5166/// is acceptable.
5167static bool CheckConvertedConstantConversions(Sema &S,
5168 StandardConversionSequence &SCS) {
5169 // Since we know that the target type is an integral or unscoped enumeration
5170 // type, most conversion kinds are impossible. All possible First and Third
5171 // conversions are fine.
5172 switch (SCS.Second) {
5173 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005174 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005175 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005176 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Egor Churaev89831422016-12-23 14:55:49 +00005177 case ICK_Zero_Queue_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005178 return true;
5179
5180 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005181 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005182 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5183 // conversion, so we allow it in a converted constant expression.
5184 //
5185 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5186 // a lot of popular code. We should at least add a warning for this
5187 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005188 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5189 SCS.getToType(2)->isBooleanType();
5190
Richard Smith410cc892014-11-26 03:26:53 +00005191 case ICK_Pointer_Conversion:
5192 case ICK_Pointer_Member:
5193 // C++1z: null pointer conversions and null member pointer conversions are
5194 // only permitted if the source type is std::nullptr_t.
5195 return SCS.getFromType()->isNullPtrType();
5196
5197 case ICK_Floating_Promotion:
5198 case ICK_Complex_Promotion:
5199 case ICK_Floating_Conversion:
5200 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005201 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005202 case ICK_Compatible_Conversion:
5203 case ICK_Derived_To_Base:
5204 case ICK_Vector_Conversion:
5205 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005206 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005207 case ICK_Block_Pointer_Conversion:
5208 case ICK_TransparentUnionConversion:
5209 case ICK_Writeback_Conversion:
5210 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005211 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005212 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005213 return false;
5214
5215 case ICK_Lvalue_To_Rvalue:
5216 case ICK_Array_To_Pointer:
5217 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005218 llvm_unreachable("found a first conversion kind in Second");
5219
Richard Smithf8379a02012-01-18 23:55:52 +00005220 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005221 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005222
5223 case ICK_Num_Conversion_Kinds:
5224 break;
5225 }
5226
5227 llvm_unreachable("unknown conversion kind");
5228}
5229
5230/// CheckConvertedConstantExpression - Check that the expression From is a
5231/// converted constant expression of type T, perform the conversion and produce
5232/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005233static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5234 QualType T, APValue &Value,
5235 Sema::CCEKind CCE,
5236 bool RequireInt) {
5237 assert(S.getLangOpts().CPlusPlus11 &&
5238 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005239
Richard Smith410cc892014-11-26 03:26:53 +00005240 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005241 return ExprError();
5242
Richard Smith410cc892014-11-26 03:26:53 +00005243 // C++1z [expr.const]p3:
5244 // A converted constant expression of type T is an expression,
5245 // implicitly converted to type T, where the converted
5246 // expression is a constant expression and the implicit conversion
5247 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005248 // C++1z [stmt.if]p2:
5249 // If the if statement is of the form if constexpr, the value of the
5250 // condition shall be a contextually converted constant expression of type
5251 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005252 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005253 CCE == Sema::CCEK_ConstexprIf
5254 ? TryContextuallyConvertToBool(S, From)
5255 : TryCopyInitialization(S, From, T,
5256 /*SuppressUserConversions=*/false,
5257 /*InOverloadResolution=*/false,
5258 /*AllowObjcWritebackConversion=*/false,
5259 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005260 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005261 switch (ICS.getKind()) {
5262 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005263 SCS = &ICS.Standard;
5264 break;
5265 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005266 // We are converting to a non-class type, so the Before sequence
5267 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005268 SCS = &ICS.UserDefined.After;
5269 break;
5270 case ImplicitConversionSequence::AmbiguousConversion:
5271 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005272 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5273 return S.Diag(From->getLocStart(),
5274 diag::err_typecheck_converted_constant_expression)
5275 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005276 return ExprError();
5277
5278 case ImplicitConversionSequence::EllipsisConversion:
5279 llvm_unreachable("ellipsis conversion in converted constant expression");
5280 }
5281
Richard Smith410cc892014-11-26 03:26:53 +00005282 // Check that we would only use permitted conversions.
5283 if (!CheckConvertedConstantConversions(S, *SCS)) {
5284 return S.Diag(From->getLocStart(),
5285 diag::err_typecheck_converted_constant_expression_disallowed)
5286 << From->getType() << From->getSourceRange() << T;
5287 }
5288 // [...] and where the reference binding (if any) binds directly.
5289 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5290 return S.Diag(From->getLocStart(),
5291 diag::err_typecheck_converted_constant_expression_indirect)
5292 << From->getType() << From->getSourceRange() << T;
5293 }
5294
5295 ExprResult Result =
5296 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005297 if (Result.isInvalid())
5298 return Result;
5299
5300 // Check for a narrowing implicit conversion.
5301 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005302 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005303 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005304 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005305 case NK_Dependent_Narrowing:
5306 // Implicit conversion to a narrower type, but the expression is
5307 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005308 case NK_Variable_Narrowing:
5309 // Implicit conversion to a narrower type, and the value is not a constant
5310 // expression. We'll diagnose this in a moment.
5311 case NK_Not_Narrowing:
5312 break;
5313
5314 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005315 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005316 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005317 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005318 break;
5319
5320 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005321 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005322 << CCE << /*Constant*/0 << From->getType() << T;
5323 break;
5324 }
5325
Richard Smith52e624f2016-12-21 21:42:57 +00005326 if (Result.get()->isValueDependent()) {
5327 Value = APValue();
5328 return Result;
5329 }
5330
Richard Smithf8379a02012-01-18 23:55:52 +00005331 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005332 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005333 Expr::EvalResult Eval;
5334 Eval.Diag = &Notes;
5335
Richard Smith410cc892014-11-26 03:26:53 +00005336 if ((T->isReferenceType()
5337 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5338 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5339 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005340 // The expression can't be folded, so we can't keep it at this position in
5341 // the AST.
5342 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005343 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005344 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005345
5346 if (Notes.empty()) {
5347 // It's a constant expression.
5348 return Result;
5349 }
Richard Smithf8379a02012-01-18 23:55:52 +00005350 }
5351
5352 // It's not a constant expression. Produce an appropriate diagnostic.
5353 if (Notes.size() == 1 &&
5354 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005355 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005356 else {
Richard Smith410cc892014-11-26 03:26:53 +00005357 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005358 << CCE << From->getSourceRange();
5359 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005360 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005361 }
Richard Smith410cc892014-11-26 03:26:53 +00005362 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005363}
5364
Richard Smith410cc892014-11-26 03:26:53 +00005365ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5366 APValue &Value, CCEKind CCE) {
5367 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5368}
5369
5370ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5371 llvm::APSInt &Value,
5372 CCEKind CCE) {
5373 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5374
5375 APValue V;
5376 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
Richard Smith01bfa682016-12-27 02:02:09 +00005377 if (!R.isInvalid() && !R.get()->isValueDependent())
Richard Smith410cc892014-11-26 03:26:53 +00005378 Value = V.getInt();
5379 return R;
5380}
5381
5382
John McCallfec112d2011-09-09 06:11:02 +00005383/// dropPointerConversions - If the given standard conversion sequence
5384/// involves any pointer conversions, remove them. This may change
5385/// the result type of the conversion sequence.
5386static void dropPointerConversion(StandardConversionSequence &SCS) {
5387 if (SCS.Second == ICK_Pointer_Conversion) {
5388 SCS.Second = ICK_Identity;
5389 SCS.Third = ICK_Identity;
5390 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5391 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005392}
John McCall5c32be02010-08-24 20:38:10 +00005393
John McCallfec112d2011-09-09 06:11:02 +00005394/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5395/// convert the expression From to an Objective-C pointer type.
5396static ImplicitConversionSequence
5397TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5398 // Do an implicit conversion to 'id'.
5399 QualType Ty = S.Context.getObjCIdType();
5400 ImplicitConversionSequence ICS
5401 = TryImplicitConversion(S, From, Ty,
5402 // FIXME: Are these flags correct?
5403 /*SuppressUserConversions=*/false,
5404 /*AllowExplicit=*/true,
5405 /*InOverloadResolution=*/false,
5406 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005407 /*AllowObjCWritebackConversion=*/false,
5408 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005409
5410 // Strip off any final conversions to 'id'.
5411 switch (ICS.getKind()) {
5412 case ImplicitConversionSequence::BadConversion:
5413 case ImplicitConversionSequence::AmbiguousConversion:
5414 case ImplicitConversionSequence::EllipsisConversion:
5415 break;
5416
5417 case ImplicitConversionSequence::UserDefinedConversion:
5418 dropPointerConversion(ICS.UserDefined.After);
5419 break;
5420
5421 case ImplicitConversionSequence::StandardConversion:
5422 dropPointerConversion(ICS.Standard);
5423 break;
5424 }
5425
5426 return ICS;
5427}
5428
5429/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5430/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005431/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005432ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005433 if (checkPlaceholderForOverload(*this, From))
5434 return ExprError();
5435
John McCall8b07ec22010-05-15 11:32:37 +00005436 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005437 ImplicitConversionSequence ICS =
5438 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005439 if (!ICS.isBad())
5440 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005441 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005442}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005443
Richard Smith8dd34252012-02-04 07:07:42 +00005444/// Determine whether the provided type is an integral type, or an enumeration
5445/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005446bool Sema::ICEConvertDiagnoser::match(QualType T) {
5447 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5448 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005449}
5450
Larisse Voufo236bec22013-06-10 06:50:24 +00005451static ExprResult
5452diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5453 Sema::ContextualImplicitConverter &Converter,
5454 QualType T, UnresolvedSetImpl &ViableConversions) {
5455
5456 if (Converter.Suppress)
5457 return ExprError();
5458
5459 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5460 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5461 CXXConversionDecl *Conv =
5462 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5463 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5464 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5465 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005466 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005467}
5468
5469static bool
5470diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5471 Sema::ContextualImplicitConverter &Converter,
5472 QualType T, bool HadMultipleCandidates,
5473 UnresolvedSetImpl &ExplicitConversions) {
5474 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5475 DeclAccessPair Found = ExplicitConversions[0];
5476 CXXConversionDecl *Conversion =
5477 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5478
5479 // The user probably meant to invoke the given explicit
5480 // conversion; use it.
5481 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5482 std::string TypeStr;
5483 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5484
5485 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5486 << FixItHint::CreateInsertion(From->getLocStart(),
5487 "static_cast<" + TypeStr + ">(")
5488 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005489 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005490 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5491
5492 // If we aren't in a SFINAE context, build a call to the
5493 // explicit conversion function.
5494 if (SemaRef.isSFINAEContext())
5495 return true;
5496
Craig Topperc3ec1492014-05-26 06:22:03 +00005497 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005498 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5499 HadMultipleCandidates);
5500 if (Result.isInvalid())
5501 return true;
5502 // Record usage of conversion in an implicit cast.
5503 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005504 CK_UserDefinedConversion, Result.get(),
5505 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005506 }
5507 return false;
5508}
5509
5510static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5511 Sema::ContextualImplicitConverter &Converter,
5512 QualType T, bool HadMultipleCandidates,
5513 DeclAccessPair &Found) {
5514 CXXConversionDecl *Conversion =
5515 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005516 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005517
5518 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5519 if (!Converter.SuppressConversion) {
5520 if (SemaRef.isSFINAEContext())
5521 return true;
5522
5523 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5524 << From->getSourceRange();
5525 }
5526
5527 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5528 HadMultipleCandidates);
5529 if (Result.isInvalid())
5530 return true;
5531 // Record usage of conversion in an implicit cast.
5532 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005533 CK_UserDefinedConversion, Result.get(),
5534 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005535 return false;
5536}
5537
5538static ExprResult finishContextualImplicitConversion(
5539 Sema &SemaRef, SourceLocation Loc, Expr *From,
5540 Sema::ContextualImplicitConverter &Converter) {
5541 if (!Converter.match(From->getType()) && !Converter.Suppress)
5542 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5543 << From->getSourceRange();
5544
5545 return SemaRef.DefaultLvalueConversion(From);
5546}
5547
5548static void
5549collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5550 UnresolvedSetImpl &ViableConversions,
5551 OverloadCandidateSet &CandidateSet) {
5552 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5553 DeclAccessPair FoundDecl = ViableConversions[I];
5554 NamedDecl *D = FoundDecl.getDecl();
5555 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5556 if (isa<UsingShadowDecl>(D))
5557 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5558
5559 CXXConversionDecl *Conv;
5560 FunctionTemplateDecl *ConvTemplate;
5561 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5562 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5563 else
5564 Conv = cast<CXXConversionDecl>(D);
5565
5566 if (ConvTemplate)
5567 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005568 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5569 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005570 else
5571 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005572 ToType, CandidateSet,
5573 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005574 }
5575}
5576
Richard Smithccc11812013-05-21 19:05:48 +00005577/// \brief Attempt to convert the given expression to a type which is accepted
5578/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005579///
Richard Smithccc11812013-05-21 19:05:48 +00005580/// This routine will attempt to convert an expression of class type to a
5581/// type accepted by the specified converter. In C++11 and before, the class
5582/// must have a single non-explicit conversion function converting to a matching
5583/// type. In C++1y, there can be multiple such conversion functions, but only
5584/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005585///
Douglas Gregor4799d032010-06-30 00:20:43 +00005586/// \param Loc The source location of the construct that requires the
5587/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005588///
James Dennett18348b62012-06-22 08:52:37 +00005589/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005590///
Richard Smithccc11812013-05-21 19:05:48 +00005591/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005592///
Douglas Gregor4799d032010-06-30 00:20:43 +00005593/// \returns The expression, converted to an integral or enumeration type if
5594/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005595ExprResult Sema::PerformContextualImplicitConversion(
5596 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005597 // We can't perform any more checking for type-dependent expressions.
5598 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005599 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005600
Eli Friedman1da70392012-01-26 00:26:18 +00005601 // Process placeholders immediately.
5602 if (From->hasPlaceholderType()) {
5603 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005604 if (result.isInvalid())
5605 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005606 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005607 }
5608
Richard Smithccc11812013-05-21 19:05:48 +00005609 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005610 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005611 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005612 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005613
5614 // FIXME: Check for missing '()' if T is a function type?
5615
Richard Smithccc11812013-05-21 19:05:48 +00005616 // We can only perform contextual implicit conversions on objects of class
5617 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005618 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005619 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005620 if (!Converter.Suppress)
5621 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005622 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005624
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005625 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005626 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005627 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005628 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005629
5630 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005631 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005632
Craig Toppere14c0f82014-03-12 04:55:44 +00005633 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005634 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005635 }
Richard Smithccc11812013-05-21 19:05:48 +00005636 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005637
Richard Smithdb0ac552015-12-18 22:40:25 +00005638 if (Converter.Suppress ? !isCompleteType(Loc, T)
5639 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005640 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005641
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005642 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005643 UnresolvedSet<4>
5644 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005645 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005646 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005647 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005648
Larisse Voufo236bec22013-06-10 06:50:24 +00005649 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005650 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005651
Larisse Voufo236bec22013-06-10 06:50:24 +00005652 // To check that there is only one target type, in C++1y:
5653 QualType ToType;
5654 bool HasUniqueTargetType = true;
5655
5656 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005657 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005658 NamedDecl *D = (*I)->getUnderlyingDecl();
5659 CXXConversionDecl *Conversion;
5660 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5661 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005662 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005663 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5664 else
5665 continue; // C++11 does not consider conversion operator templates(?).
5666 } else
5667 Conversion = cast<CXXConversionDecl>(D);
5668
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005669 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005670 "Conversion operator templates are considered potentially "
5671 "viable in C++1y");
5672
5673 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5674 if (Converter.match(CurToType) || ConvTemplate) {
5675
5676 if (Conversion->isExplicit()) {
5677 // FIXME: For C++1y, do we need this restriction?
5678 // cf. diagnoseNoViableConversion()
5679 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005680 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005681 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005682 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005683 if (ToType.isNull())
5684 ToType = CurToType.getUnqualifiedType();
5685 else if (HasUniqueTargetType &&
5686 (CurToType.getUnqualifiedType() != ToType))
5687 HasUniqueTargetType = false;
5688 }
5689 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005690 }
Richard Smith8dd34252012-02-04 07:07:42 +00005691 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005692 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005693
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005694 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005695 // C++1y [conv]p6:
5696 // ... An expression e of class type E appearing in such a context
5697 // is said to be contextually implicitly converted to a specified
5698 // type T and is well-formed if and only if e can be implicitly
5699 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005700 // for conversion functions whose return type is cv T or reference to
5701 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005702 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005703
Larisse Voufo236bec22013-06-10 06:50:24 +00005704 // If no unique T is found:
5705 if (ToType.isNull()) {
5706 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5707 HadMultipleCandidates,
5708 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005709 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005710 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005712
Larisse Voufo236bec22013-06-10 06:50:24 +00005713 // If more than one unique Ts are found:
5714 if (!HasUniqueTargetType)
5715 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5716 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005717
Larisse Voufo236bec22013-06-10 06:50:24 +00005718 // If one unique T is found:
5719 // First, build a candidate set from the previously recorded
5720 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005721 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005722 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5723 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005724
Larisse Voufo236bec22013-06-10 06:50:24 +00005725 // Then, perform overload resolution over the candidate set.
5726 OverloadCandidateSet::iterator Best;
5727 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5728 case OR_Success: {
5729 // Apply this conversion.
5730 DeclAccessPair Found =
5731 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5732 if (recordConversion(*this, Loc, From, Converter, T,
5733 HadMultipleCandidates, Found))
5734 return ExprError();
5735 break;
5736 }
5737 case OR_Ambiguous:
5738 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5739 ViableConversions);
5740 case OR_No_Viable_Function:
5741 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5742 HadMultipleCandidates,
5743 ExplicitConversions))
5744 return ExprError();
5745 // fall through 'OR_Deleted' case.
5746 case OR_Deleted:
5747 // We'll complain below about a non-integral condition type.
5748 break;
5749 }
5750 } else {
5751 switch (ViableConversions.size()) {
5752 case 0: {
5753 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5754 HadMultipleCandidates,
5755 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005756 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005757
Larisse Voufo236bec22013-06-10 06:50:24 +00005758 // We'll complain below about a non-integral condition type.
5759 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005760 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005761 case 1: {
5762 // Apply this conversion.
5763 DeclAccessPair Found = ViableConversions[0];
5764 if (recordConversion(*this, Loc, From, Converter, T,
5765 HadMultipleCandidates, Found))
5766 return ExprError();
5767 break;
5768 }
5769 default:
5770 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5771 ViableConversions);
5772 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005774
Larisse Voufo236bec22013-06-10 06:50:24 +00005775 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005776}
5777
Richard Smith100b24a2014-04-17 01:52:14 +00005778/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5779/// an acceptable non-member overloaded operator for a call whose
5780/// arguments have types T1 (and, if non-empty, T2). This routine
5781/// implements the check in C++ [over.match.oper]p3b2 concerning
5782/// enumeration types.
5783static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5784 FunctionDecl *Fn,
5785 ArrayRef<Expr *> Args) {
5786 QualType T1 = Args[0]->getType();
5787 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5788
5789 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5790 return true;
5791
5792 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5793 return true;
5794
5795 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5796 if (Proto->getNumParams() < 1)
5797 return false;
5798
5799 if (T1->isEnumeralType()) {
5800 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5801 if (Context.hasSameUnqualifiedType(T1, ArgType))
5802 return true;
5803 }
5804
5805 if (Proto->getNumParams() < 2)
5806 return false;
5807
5808 if (!T2.isNull() && T2->isEnumeralType()) {
5809 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5810 if (Context.hasSameUnqualifiedType(T2, ArgType))
5811 return true;
5812 }
5813
5814 return false;
5815}
5816
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005817/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005818/// candidate functions, using the given function call arguments. If
5819/// @p SuppressUserConversions, then don't allow user-defined
5820/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005821///
James Dennett2a4d13c2012-06-15 07:13:21 +00005822/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005823/// based on an incomplete set of function arguments. This feature is used by
5824/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005825void
5826Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005827 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005828 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005829 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005830 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005831 bool PartialOverloading,
Renato Golindad96d62017-01-02 11:15:42 +00005832 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005833 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005834 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005835 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005836 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005837 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005838
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005839 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005840 if (!isa<CXXConstructorDecl>(Method)) {
5841 // If we get here, it's because we're calling a member function
5842 // that is named without a member access expression (e.g.,
5843 // "this->f") that was either written explicitly or created
5844 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005845 // function, e.g., X::f(). We use an empty type for the implied
5846 // object argument (C++ [over.call.func]p3), and the acting context
5847 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005848 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005849 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005850 Args, CandidateSet, SuppressUserConversions,
Renato Golindad96d62017-01-02 11:15:42 +00005851 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005852 return;
5853 }
5854 // We treat a constructor like a non-member function, since its object
5855 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005856 }
5857
Douglas Gregorff7028a2009-11-13 23:59:09 +00005858 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005859 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005860
Richard Smith100b24a2014-04-17 01:52:14 +00005861 // C++ [over.match.oper]p3:
5862 // if no operand has a class type, only those non-member functions in the
5863 // lookup set that have a first parameter of type T1 or "reference to
5864 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5865 // is a right operand) a second parameter of type T2 or "reference to
5866 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5867 // candidate functions.
5868 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5869 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5870 return;
5871
Richard Smith8b86f2d2013-11-04 01:48:18 +00005872 // C++11 [class.copy]p11: [DR1402]
5873 // A defaulted move constructor that is defined as deleted is ignored by
5874 // overload resolution.
5875 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5876 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5877 Constructor->isMoveConstructor())
5878 return;
5879
Douglas Gregor27381f32009-11-23 12:27:39 +00005880 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005881 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005882
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005883 // Add this candidate
Renato Golindad96d62017-01-02 11:15:42 +00005884 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005885 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005886 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005887 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005888 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005889 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005890 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005891
John McCall578a1f82014-12-14 01:46:53 +00005892 if (Constructor) {
5893 // C++ [class.copy]p3:
5894 // A member function template is never instantiated to perform the copy
5895 // of a class object to an object of its class type.
5896 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005897 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005898 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005899 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5900 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005901 Candidate.Viable = false;
5902 Candidate.FailureKind = ovl_fail_illegal_constructor;
5903 return;
5904 }
5905 }
5906
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005907 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005908
5909 // (C++ 13.3.2p2): A candidate function having fewer than m
5910 // parameters is viable only if it has an ellipsis in its parameter
5911 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005912 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005913 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005914 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005915 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005916 return;
5917 }
5918
5919 // (C++ 13.3.2p2): A candidate function having more than m parameters
5920 // is viable only if the (m+1)st parameter has a default argument
5921 // (8.3.6). For the purposes of overload resolution, the
5922 // parameter list is truncated on the right, so that there are
5923 // exactly m parameters.
5924 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005925 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005926 // Not enough arguments.
5927 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005928 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005929 return;
5930 }
5931
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005932 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005933 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005934 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005935 // Skip the check for callers that are implicit members, because in this
5936 // case we may not yet know what the member's target is; the target is
5937 // inferred for the member automatically, based on the bases and fields of
5938 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00005939 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005940 Candidate.Viable = false;
5941 Candidate.FailureKind = ovl_fail_bad_target;
5942 return;
5943 }
5944
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005945 // Determine the implicit conversion sequences for each of the
5946 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005947 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Renato Golindad96d62017-01-02 11:15:42 +00005948 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005949 // (C++ 13.3.2p3): for F to be a viable function, there shall
5950 // exist for each argument an implicit conversion sequence
5951 // (13.3.3.1) that converts that argument to the corresponding
5952 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005953 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005954 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005955 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005956 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005957 /*InOverloadResolution=*/true,
5958 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005959 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005960 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005961 if (Candidate.Conversions[ArgIdx].isBad()) {
5962 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005963 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005964 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005965 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005966 } else {
5967 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5968 // argument for which there is no corresponding parameter is
5969 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005970 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005971 }
5972 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005973
5974 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5975 Candidate.Viable = false;
5976 Candidate.FailureKind = ovl_fail_enable_if;
5977 Candidate.DeductionFailure.Data = FailedAttr;
5978 return;
5979 }
Yaxun Liu5b746652016-12-18 05:18:55 +00005980
5981 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
5982 Candidate.Viable = false;
5983 Candidate.FailureKind = ovl_fail_ext_disabled;
5984 return;
5985 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005986}
5987
Manman Rend2a3cd72016-04-07 19:30:20 +00005988ObjCMethodDecl *
5989Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5990 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5991 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005992 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00005993
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005994 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5995 bool Match = true;
5996 ObjCMethodDecl *Method = Methods[b];
5997 unsigned NumNamedArgs = Sel.getNumArgs();
5998 // Method might have more arguments than selector indicates. This is due
5999 // to addition of c-style arguments in method.
6000 if (Method->param_size() > NumNamedArgs)
6001 NumNamedArgs = Method->param_size();
6002 if (Args.size() < NumNamedArgs)
6003 continue;
6004
6005 for (unsigned i = 0; i < NumNamedArgs; i++) {
6006 // We can't do any type-checking on a type-dependent argument.
6007 if (Args[i]->isTypeDependent()) {
6008 Match = false;
6009 break;
6010 }
6011
6012 ParmVarDecl *param = Method->parameters()[i];
6013 Expr *argExpr = Args[i];
6014 assert(argExpr && "SelectBestMethod(): missing expression");
6015
6016 // Strip the unbridged-cast placeholder expression off unless it's
6017 // a consumed argument.
6018 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6019 !param->hasAttr<CFConsumedAttr>())
6020 argExpr = stripARCUnbridgedCast(argExpr);
6021
6022 // If the parameter is __unknown_anytype, move on to the next method.
6023 if (param->getType() == Context.UnknownAnyTy) {
6024 Match = false;
6025 break;
6026 }
George Burgess IV45461812015-10-11 20:13:20 +00006027
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006028 ImplicitConversionSequence ConversionState
6029 = TryCopyInitialization(*this, argExpr, param->getType(),
6030 /*SuppressUserConversions*/false,
6031 /*InOverloadResolution=*/true,
6032 /*AllowObjCWritebackConversion=*/
6033 getLangOpts().ObjCAutoRefCount,
6034 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006035 // This function looks for a reasonably-exact match, so we consider
6036 // incompatible pointer conversions to be a failure here.
6037 if (ConversionState.isBad() ||
6038 (ConversionState.isStandard() &&
6039 ConversionState.Standard.Second ==
6040 ICK_Incompatible_Pointer_Conversion)) {
6041 Match = false;
6042 break;
6043 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006044 }
6045 // Promote additional arguments to variadic methods.
6046 if (Match && Method->isVariadic()) {
6047 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6048 if (Args[i]->isTypeDependent()) {
6049 Match = false;
6050 break;
6051 }
6052 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6053 nullptr);
6054 if (Arg.isInvalid()) {
6055 Match = false;
6056 break;
6057 }
6058 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006059 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006060 // Check for extra arguments to non-variadic methods.
6061 if (Args.size() != NumNamedArgs)
6062 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006063 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6064 // Special case when selectors have no argument. In this case, select
6065 // one with the most general result type of 'id'.
6066 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6067 QualType ReturnT = Methods[b]->getReturnType();
6068 if (ReturnT->isObjCIdType())
6069 return Methods[b];
6070 }
6071 }
6072 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006073
6074 if (Match)
6075 return Method;
6076 }
6077 return nullptr;
6078}
6079
George Burgess IV2a6150d2015-10-16 01:17:38 +00006080// specific_attr_iterator iterates over enable_if attributes in reverse, and
6081// enable_if is order-sensitive. As a result, we need to reverse things
6082// sometimes. Size of 4 elements is arbitrary.
6083static SmallVector<EnableIfAttr *, 4>
6084getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6085 SmallVector<EnableIfAttr *, 4> Result;
6086 if (!Function->hasAttrs())
6087 return Result;
6088
6089 const auto &FuncAttrs = Function->getAttrs();
6090 for (Attr *Attr : FuncAttrs)
6091 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6092 Result.push_back(EnableIf);
6093
6094 std::reverse(Result.begin(), Result.end());
6095 return Result;
6096}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006097
6098EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6099 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00006100 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6101 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00006102 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006103
6104 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006105 SmallVector<Expr *, 16> ConvertedArgs;
6106 bool InitializationFailed = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006107
George Burgess IV458b3f32016-08-12 04:19:35 +00006108 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV53b938d2016-08-12 04:12:31 +00006109 // user can't refer to them in the enable_if condition.
6110 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6111
Nick Lewyckye283c552015-08-25 22:33:16 +00006112 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006113 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006114 ExprResult R;
6115 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00006116 !cast<CXXMethodDecl>(Function)->isStatic() &&
6117 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006118 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
George Burgess IVe96abf72016-02-24 22:31:14 +00006119 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6120 Method, Method);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006121 } else {
George Burgess IVe96abf72016-02-24 22:31:14 +00006122 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6123 Context, Function->getParamDecl(I)),
6124 SourceLocation(), Args[I]);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006125 }
George Burgess IVe96abf72016-02-24 22:31:14 +00006126
6127 if (R.isInvalid()) {
6128 InitializationFailed = true;
6129 break;
6130 }
6131
George Burgess IVe96abf72016-02-24 22:31:14 +00006132 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006133 }
6134
6135 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006136 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006137
Nick Lewyckye283c552015-08-25 22:33:16 +00006138 // Push default arguments if needed.
6139 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6140 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6141 ParmVarDecl *P = Function->getParamDecl(i);
6142 ExprResult R = PerformCopyInitialization(
6143 InitializedEntity::InitializeParameter(Context,
6144 Function->getParamDecl(i)),
6145 SourceLocation(),
6146 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6147 : P->getDefaultArg());
6148 if (R.isInvalid()) {
6149 InitializationFailed = true;
6150 break;
6151 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006152 ConvertedArgs.push_back(R.get());
6153 }
6154
6155 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006156 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006157 }
6158
George Burgess IV2a6150d2015-10-16 01:17:38 +00006159 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006160 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006161 // FIXME: This doesn't consider value-dependent cases, because doing so is
6162 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006163 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006164 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006165 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006166
6167 if (!Result.isInt() || !Result.getInt().getBoolValue())
6168 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006169 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006170 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006171}
6172
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006173/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006174/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006175void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006176 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006177 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006178 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006179 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006180 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006181 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006182 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6183 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006184 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006185 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006186 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006187 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006188 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006189 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006190 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006191 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006192 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006193 } else {
John McCalla0296f72010-03-19 07:35:19 +00006194 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006195 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6196 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006197 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006198 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006199 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006200 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006201 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006202 CandidateSet, SuppressUserConversions,
6203 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006204 else
John McCalla0296f72010-03-19 07:35:19 +00006205 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006206 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006207 CandidateSet, SuppressUserConversions,
6208 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006209 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006210 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006211}
6212
John McCallf0f1cf02009-11-17 07:50:12 +00006213/// AddMethodCandidate - Adds a named decl (which is some kind of
6214/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006215void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006216 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006217 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006218 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006219 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006220 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006221 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006222 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006223
6224 if (isa<UsingShadowDecl>(Decl))
6225 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006226
John McCallf0f1cf02009-11-17 07:50:12 +00006227 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6228 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6229 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006230 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006231 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006232 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006233 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006234 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006235 } else {
John McCalla0296f72010-03-19 07:35:19 +00006236 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006237 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006238 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006239 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006240 }
6241}
6242
Douglas Gregor436424c2008-11-18 23:14:02 +00006243/// AddMethodCandidate - Adds the given C++ member function to the set
6244/// of candidate functions, using the given function call arguments
6245/// and the object argument (@c Object). For example, in a call
6246/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6247/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6248/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006249/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006250void
John McCalla0296f72010-03-19 07:35:19 +00006251Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006252 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006253 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006254 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006255 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006256 bool SuppressUserConversions,
Renato Golindad96d62017-01-02 11:15:42 +00006257 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006258 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006259 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006260 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006261 assert(!isa<CXXConstructorDecl>(Method) &&
6262 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006263
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006264 if (!CandidateSet.isNewCandidate(Method))
6265 return;
6266
Richard Smith8b86f2d2013-11-04 01:48:18 +00006267 // C++11 [class.copy]p23: [DR1402]
6268 // A defaulted move assignment operator that is defined as deleted is
6269 // ignored by overload resolution.
6270 if (Method->isDefaulted() && Method->isDeleted() &&
6271 Method->isMoveAssignmentOperator())
6272 return;
6273
Douglas Gregor27381f32009-11-23 12:27:39 +00006274 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006275 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006276
Douglas Gregor436424c2008-11-18 23:14:02 +00006277 // Add this candidate
Renato Golindad96d62017-01-02 11:15:42 +00006278 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006279 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006280 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006281 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006282 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006283 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006284
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006285 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006286
6287 // (C++ 13.3.2p2): A candidate function having fewer than m
6288 // parameters is viable only if it has an ellipsis in its parameter
6289 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006290 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6291 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006292 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006293 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006294 return;
6295 }
6296
6297 // (C++ 13.3.2p2): A candidate function having more than m parameters
6298 // is viable only if the (m+1)st parameter has a default argument
6299 // (8.3.6). For the purposes of overload resolution, the
6300 // parameter list is truncated on the right, so that there are
6301 // exactly m parameters.
6302 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006303 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006304 // Not enough arguments.
6305 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006306 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006307 return;
6308 }
6309
6310 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006311
John McCall6e9f8f62009-12-03 04:06:58 +00006312 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006313 // The implicit object argument is ignored.
6314 Candidate.IgnoreObjectArgument = true;
6315 else {
6316 // Determine the implicit conversion sequence for the object
6317 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006318 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6319 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6320 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006321 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006322 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006323 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006324 return;
6325 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006326 }
6327
Eli Bendersky291a57e2014-09-25 23:59:08 +00006328 // (CUDA B.1): Check for invalid calls between targets.
6329 if (getLangOpts().CUDA)
6330 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006331 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006332 Candidate.Viable = false;
6333 Candidate.FailureKind = ovl_fail_bad_target;
6334 return;
6335 }
6336
Douglas Gregor436424c2008-11-18 23:14:02 +00006337 // Determine the implicit conversion sequences for each of the
6338 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006339 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Renato Golindad96d62017-01-02 11:15:42 +00006340 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006341 // (C++ 13.3.2p3): for F to be a viable function, there shall
6342 // exist for each argument an implicit conversion sequence
6343 // (13.3.3.1) that converts that argument to the corresponding
6344 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006345 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006346 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006347 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006348 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006349 /*InOverloadResolution=*/true,
6350 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006351 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006352 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006353 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006354 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006355 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006356 }
6357 } else {
6358 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6359 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006360 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006361 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006362 }
6363 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006364
6365 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6366 Candidate.Viable = false;
6367 Candidate.FailureKind = ovl_fail_enable_if;
6368 Candidate.DeductionFailure.Data = FailedAttr;
6369 return;
6370 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006371}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006372
Douglas Gregor97628d62009-08-21 00:16:32 +00006373/// \brief Add a C++ member function template as a candidate to the candidate
6374/// set, using template argument deduction to produce an appropriate member
6375/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006376void
Douglas Gregor97628d62009-08-21 00:16:32 +00006377Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006378 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006379 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006380 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006381 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006382 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006383 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006384 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006385 bool SuppressUserConversions,
6386 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006387 if (!CandidateSet.isNewCandidate(MethodTmpl))
6388 return;
6389
Douglas Gregor97628d62009-08-21 00:16:32 +00006390 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006391 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006392 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006393 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006394 // candidate functions in the usual way.113) A given name can refer to one
6395 // or more function templates and also to a set of overloaded non-template
6396 // functions. In such a case, the candidate functions generated from each
6397 // function template are combined with the set of non-template candidate
6398 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006399 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006400 FunctionDecl *Specialization = nullptr;
Renato Golindad96d62017-01-02 11:15:42 +00006401 if (TemplateDeductionResult Result
6402 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6403 Specialization, Info, PartialOverloading)) {
6404 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006405 Candidate.FoundDecl = FoundDecl;
6406 Candidate.Function = MethodTmpl->getTemplatedDecl();
6407 Candidate.Viable = false;
Renato Golindad96d62017-01-02 11:15:42 +00006408 Candidate.FailureKind = ovl_fail_bad_deduction;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006409 Candidate.IsSurrogate = false;
6410 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006411 Candidate.ExplicitCallArguments = Args.size();
Renato Golindad96d62017-01-02 11:15:42 +00006412 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6413 Info);
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006414 return;
6415 }
Mike Stump11289f42009-09-09 15:08:12 +00006416
Douglas Gregor97628d62009-08-21 00:16:32 +00006417 // Add the function template specialization produced by template argument
6418 // deduction as a candidate.
6419 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006420 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006421 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006422 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006423 ActingContext, ObjectType, ObjectClassification, Args,
Renato Golindad96d62017-01-02 11:15:42 +00006424 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006425}
6426
Douglas Gregor05155d82009-08-21 23:19:43 +00006427/// \brief Add a C++ function template specialization as a candidate
6428/// in the candidate set, using template argument deduction to produce
6429/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006430void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006431Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006432 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006433 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006434 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006435 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006436 bool SuppressUserConversions,
6437 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006438 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6439 return;
6440
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006441 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006442 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006443 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006444 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006445 // candidate functions in the usual way.113) A given name can refer to one
6446 // or more function templates and also to a set of overloaded non-template
6447 // functions. In such a case, the candidate functions generated from each
6448 // function template are combined with the set of non-template candidate
6449 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006450 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006451 FunctionDecl *Specialization = nullptr;
Renato Golindad96d62017-01-02 11:15:42 +00006452 if (TemplateDeductionResult Result
6453 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6454 Specialization, Info, PartialOverloading)) {
6455 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006456 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006457 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6458 Candidate.Viable = false;
Renato Golindad96d62017-01-02 11:15:42 +00006459 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006460 Candidate.IsSurrogate = false;
6461 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006462 Candidate.ExplicitCallArguments = Args.size();
Renato Golindad96d62017-01-02 11:15:42 +00006463 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6464 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006465 return;
6466 }
Mike Stump11289f42009-09-09 15:08:12 +00006467
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006468 // Add the function template specialization produced by template argument
6469 // deduction as a candidate.
6470 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006471 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Renato Golindad96d62017-01-02 11:15:42 +00006472 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006473}
Mike Stump11289f42009-09-09 15:08:12 +00006474
Douglas Gregor4b60a152013-11-07 22:34:54 +00006475/// Determine whether this is an allowable conversion from the result
6476/// of an explicit conversion operator to the expected type, per C++
6477/// [over.match.conv]p1 and [over.match.ref]p1.
6478///
6479/// \param ConvType The return type of the conversion function.
6480///
6481/// \param ToType The type we are converting to.
6482///
6483/// \param AllowObjCPointerConversion Allow a conversion from one
6484/// Objective-C pointer to another.
6485///
6486/// \returns true if the conversion is allowable, false otherwise.
6487static bool isAllowableExplicitConversion(Sema &S,
6488 QualType ConvType, QualType ToType,
6489 bool AllowObjCPointerConversion) {
6490 QualType ToNonRefType = ToType.getNonReferenceType();
6491
6492 // Easy case: the types are the same.
6493 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6494 return true;
6495
6496 // Allow qualification conversions.
6497 bool ObjCLifetimeConversion;
6498 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6499 ObjCLifetimeConversion))
6500 return true;
6501
6502 // If we're not allowed to consider Objective-C pointer conversions,
6503 // we're done.
6504 if (!AllowObjCPointerConversion)
6505 return false;
6506
6507 // Is this an Objective-C pointer conversion?
6508 bool IncompatibleObjC = false;
6509 QualType ConvertedType;
6510 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6511 IncompatibleObjC);
6512}
6513
Douglas Gregora1f013e2008-11-07 22:36:19 +00006514/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006515/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006516/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006517/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006518/// (which may or may not be the same type as the type that the
6519/// conversion function produces).
6520void
6521Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006522 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006523 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006524 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006525 OverloadCandidateSet& CandidateSet,
6526 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006527 assert(!Conversion->getDescribedFunctionTemplate() &&
6528 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006529 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006530 if (!CandidateSet.isNewCandidate(Conversion))
6531 return;
6532
Richard Smith2a7d4812013-05-04 07:00:32 +00006533 // If the conversion function has an undeduced return type, trigger its
6534 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006535 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006536 if (DeduceReturnType(Conversion, From->getExprLoc()))
6537 return;
6538 ConvType = Conversion->getConversionType().getNonReferenceType();
6539 }
6540
Richard Smith089c3162013-09-21 21:55:46 +00006541 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6542 // operator is only a candidate if its return type is the target type or
6543 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006544 if (Conversion->isExplicit() &&
6545 !isAllowableExplicitConversion(*this, ConvType, ToType,
6546 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006547 return;
6548
Douglas Gregor27381f32009-11-23 12:27:39 +00006549 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006550 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006551
Douglas Gregora1f013e2008-11-07 22:36:19 +00006552 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006553 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006554 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006555 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006556 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006557 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006558 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006559 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006560 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006561 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006562 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006563
Douglas Gregor6affc782010-08-19 15:37:02 +00006564 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006565 // For conversion functions, the function is considered to be a member of
6566 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006567 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006568 //
6569 // Determine the implicit conversion sequence for the implicit
6570 // object parameter.
6571 QualType ImplicitParamType = From->getType();
6572 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6573 ImplicitParamType = FromPtrType->getPointeeType();
6574 CXXRecordDecl *ConversionContext
6575 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006576
Richard Smith0f59cb32015-12-18 21:45:41 +00006577 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6578 *this, CandidateSet.getLocation(), From->getType(),
6579 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006580
John McCall0d1da222010-01-12 00:44:57 +00006581 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006582 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006583 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006584 return;
6585 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006586
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006587 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006588 // derived to base as such conversions are given Conversion Rank. They only
6589 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6590 QualType FromCanon
6591 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6592 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006593 if (FromCanon == ToCanon ||
6594 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006595 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006596 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006597 return;
6598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006599
Douglas Gregora1f013e2008-11-07 22:36:19 +00006600 // To determine what the conversion from the result of calling the
6601 // conversion function to the type we're eventually trying to
6602 // convert to (ToType), we need to synthesize a call to the
6603 // conversion function and attempt copy initialization from it. This
6604 // makes sure that we get the right semantics with respect to
6605 // lvalues/rvalues and the type. Fortunately, we can allocate this
6606 // call on the stack and we don't need its arguments to be
6607 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006608 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006609 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006610 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6611 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006612 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006613 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006614
Richard Smith48d24642011-07-13 22:53:21 +00006615 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006616 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006617 Candidate.Viable = false;
6618 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6619 return;
6620 }
6621
Richard Smith48d24642011-07-13 22:53:21 +00006622 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006623
Mike Stump11289f42009-09-09 15:08:12 +00006624 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006625 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6626 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006627 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006628 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006629 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006630 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006631 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006632 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006633 /*InOverloadResolution=*/false,
6634 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006635
John McCall0d1da222010-01-12 00:44:57 +00006636 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006637 case ImplicitConversionSequence::StandardConversion:
6638 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006639
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006640 // C++ [over.ics.user]p3:
6641 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006642 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006643 // shall have exact match rank.
6644 if (Conversion->getPrimaryTemplate() &&
6645 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6646 Candidate.Viable = false;
6647 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006648 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006649 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006650
Douglas Gregorcba72b12011-01-21 05:18:22 +00006651 // C++0x [dcl.init.ref]p5:
6652 // In the second case, if the reference is an rvalue reference and
6653 // the second standard conversion sequence of the user-defined
6654 // conversion sequence includes an lvalue-to-rvalue conversion, the
6655 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006656 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006657 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6658 Candidate.Viable = false;
6659 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006660 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006661 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006662 break;
6663
6664 case ImplicitConversionSequence::BadConversion:
6665 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006666 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006667 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006668
6669 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006670 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006671 "Can only end up with a standard conversion sequence or failure");
6672 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006673
Craig Topper5fc8fc22014-08-27 06:28:36 +00006674 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006675 Candidate.Viable = false;
6676 Candidate.FailureKind = ovl_fail_enable_if;
6677 Candidate.DeductionFailure.Data = FailedAttr;
6678 return;
6679 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006680}
6681
Douglas Gregor05155d82009-08-21 23:19:43 +00006682/// \brief Adds a conversion function template specialization
6683/// candidate to the overload set, using template argument deduction
6684/// to deduce the template arguments of the conversion function
6685/// template from the type that we are converting to (C++
6686/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006687void
Douglas Gregor05155d82009-08-21 23:19:43 +00006688Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006689 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006690 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006691 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006692 OverloadCandidateSet &CandidateSet,
6693 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006694 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6695 "Only conversion function templates permitted here");
6696
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006697 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6698 return;
6699
Craig Toppere6706e42012-09-19 02:26:47 +00006700 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006701 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006702 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006703 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006704 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006705 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006706 Candidate.FoundDecl = FoundDecl;
6707 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6708 Candidate.Viable = false;
6709 Candidate.FailureKind = ovl_fail_bad_deduction;
6710 Candidate.IsSurrogate = false;
6711 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006712 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006713 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006714 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006715 return;
6716 }
Mike Stump11289f42009-09-09 15:08:12 +00006717
Douglas Gregor05155d82009-08-21 23:19:43 +00006718 // Add the conversion function template specialization produced by
6719 // template argument deduction as a candidate.
6720 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006721 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006722 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006723}
6724
Douglas Gregorab7897a2008-11-19 22:57:39 +00006725/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6726/// converts the given @c Object to a function pointer via the
6727/// conversion function @c Conversion, and then attempts to call it
6728/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6729/// the type of function that we'll eventually be calling.
6730void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006731 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006732 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006733 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006734 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006735 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006736 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006737 if (!CandidateSet.isNewCandidate(Conversion))
6738 return;
6739
Douglas Gregor27381f32009-11-23 12:27:39 +00006740 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006741 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006742
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006743 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006744 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006745 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006746 Candidate.Surrogate = Conversion;
6747 Candidate.Viable = true;
6748 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006749 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006750 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006751
6752 // Determine the implicit conversion sequence for the implicit
6753 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006754 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6755 *this, CandidateSet.getLocation(), Object->getType(),
6756 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006757 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006758 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006759 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006760 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006761 return;
6762 }
6763
6764 // The first conversion is actually a user-defined conversion whose
6765 // first conversion is ObjectInit's standard conversion (which is
6766 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006767 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006768 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006769 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006770 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006771 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006772 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006773 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006774 = Candidate.Conversions[0].UserDefined.Before;
6775 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6776
Mike Stump11289f42009-09-09 15:08:12 +00006777 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006778 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006779
6780 // (C++ 13.3.2p2): A candidate function having fewer than m
6781 // parameters is viable only if it has an ellipsis in its parameter
6782 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006783 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006784 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006785 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006786 return;
6787 }
6788
6789 // Function types don't have any default arguments, so just check if
6790 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006791 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006792 // Not enough arguments.
6793 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006794 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006795 return;
6796 }
6797
6798 // Determine the implicit conversion sequences for each of the
6799 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006800 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006801 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006802 // (C++ 13.3.2p3): for F to be a viable function, there shall
6803 // exist for each argument an implicit conversion sequence
6804 // (13.3.3.1) that converts that argument to the corresponding
6805 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006806 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006807 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006808 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006809 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006810 /*InOverloadResolution=*/false,
6811 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006812 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006813 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006814 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006815 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006816 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006817 }
6818 } else {
6819 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6820 // argument for which there is no corresponding parameter is
6821 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006822 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006823 }
6824 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006825
Craig Topper5fc8fc22014-08-27 06:28:36 +00006826 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006827 Candidate.Viable = false;
6828 Candidate.FailureKind = ovl_fail_enable_if;
6829 Candidate.DeductionFailure.Data = FailedAttr;
6830 return;
6831 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006832}
6833
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006834/// \brief Add overload candidates for overloaded operators that are
6835/// member functions.
6836///
6837/// Add the overloaded operator candidates that are member functions
6838/// for the operator Op that was used in an operator expression such
6839/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6840/// CandidateSet will store the added overload candidates. (C++
6841/// [over.match.oper]).
6842void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6843 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006844 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006845 OverloadCandidateSet& CandidateSet,
6846 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006847 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6848
6849 // C++ [over.match.oper]p3:
6850 // For a unary operator @ with an operand of a type whose
6851 // cv-unqualified version is T1, and for a binary operator @ with
6852 // a left operand of a type whose cv-unqualified version is T1 and
6853 // a right operand of a type whose cv-unqualified version is T2,
6854 // three sets of candidate functions, designated member
6855 // candidates, non-member candidates and built-in candidates, are
6856 // constructed as follows:
6857 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006858
Richard Smith0feaf0c2013-04-20 12:41:22 +00006859 // -- If T1 is a complete class type or a class currently being
6860 // defined, the set of member candidates is the result of the
6861 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6862 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006863 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006864 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006865 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006866 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006867 // If the type is neither complete nor being defined, bail out now.
6868 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006869 return;
Mike Stump11289f42009-09-09 15:08:12 +00006870
John McCall27b18f82009-11-17 02:14:36 +00006871 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6872 LookupQualifiedName(Operators, T1Rec->getDecl());
6873 Operators.suppressDiagnostics();
6874
Mike Stump11289f42009-09-09 15:08:12 +00006875 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006876 OperEnd = Operators.end();
6877 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006878 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006879 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006880 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006881 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006882 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006883 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006884 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006885}
6886
Douglas Gregora11693b2008-11-12 17:17:38 +00006887/// AddBuiltinCandidate - Add a candidate for a built-in
6888/// operator. ResultTy and ParamTys are the result and parameter types
6889/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006890/// arguments being passed to the candidate. IsAssignmentOperator
6891/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006892/// operator. NumContextualBoolArguments is the number of arguments
6893/// (at the beginning of the argument list) that will be contextually
6894/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006895void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006896 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006897 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006898 bool IsAssignmentOperator,
6899 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006900 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006901 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006902
Douglas Gregora11693b2008-11-12 17:17:38 +00006903 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006904 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006905 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6906 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006907 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006908 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006909 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006910 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006911 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6912
6913 // Determine the implicit conversion sequences for each of the
6914 // arguments.
6915 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006916 Candidate.ExplicitCallArguments = Args.size();
6917 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006918 // C++ [over.match.oper]p4:
6919 // For the built-in assignment operators, conversions of the
6920 // left operand are restricted as follows:
6921 // -- no temporaries are introduced to hold the left operand, and
6922 // -- no user-defined conversions are applied to the left
6923 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006924 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006925 //
6926 // We block these conversions by turning off user-defined
6927 // conversions, since that is the only way that initialization of
6928 // a reference to a non-class type can occur from something that
6929 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006930 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006931 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006932 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006933 Candidate.Conversions[ArgIdx]
6934 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006935 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006936 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006937 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006938 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006939 /*InOverloadResolution=*/false,
6940 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006941 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006942 }
John McCall0d1da222010-01-12 00:44:57 +00006943 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006944 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006945 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006946 break;
6947 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006948 }
6949}
6950
Craig Toppercd7b0332013-07-01 06:29:40 +00006951namespace {
6952
Douglas Gregora11693b2008-11-12 17:17:38 +00006953/// BuiltinCandidateTypeSet - A set of types that will be used for the
6954/// candidate operator functions for built-in operators (C++
6955/// [over.built]). The types are separated into pointer types and
6956/// enumeration types.
6957class BuiltinCandidateTypeSet {
6958 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00006959 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6960 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006961
6962 /// PointerTypes - The set of pointer types that will be used in the
6963 /// built-in candidates.
6964 TypeSet PointerTypes;
6965
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006966 /// MemberPointerTypes - The set of member pointer types that will be
6967 /// used in the built-in candidates.
6968 TypeSet MemberPointerTypes;
6969
Douglas Gregora11693b2008-11-12 17:17:38 +00006970 /// EnumerationTypes - The set of enumeration types that will be
6971 /// used in the built-in candidates.
6972 TypeSet EnumerationTypes;
6973
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006974 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006975 /// candidates.
6976 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006977
6978 /// \brief A flag indicating non-record types are viable candidates
6979 bool HasNonRecordTypes;
6980
6981 /// \brief A flag indicating whether either arithmetic or enumeration types
6982 /// were present in the candidate set.
6983 bool HasArithmeticOrEnumeralTypes;
6984
Douglas Gregor80af3132011-05-21 23:15:46 +00006985 /// \brief A flag indicating whether the nullptr type was present in the
6986 /// candidate set.
6987 bool HasNullPtrType;
6988
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006989 /// Sema - The semantic analysis instance where we are building the
6990 /// candidate type set.
6991 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006992
Douglas Gregora11693b2008-11-12 17:17:38 +00006993 /// Context - The AST context in which we will build the type sets.
6994 ASTContext &Context;
6995
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006996 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6997 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006998 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006999
7000public:
7001 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007002 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007003
Mike Stump11289f42009-09-09 15:08:12 +00007004 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007005 : HasNonRecordTypes(false),
7006 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007007 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007008 SemaRef(SemaRef),
7009 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007010
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007011 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007012 SourceLocation Loc,
7013 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007014 bool AllowExplicitConversions,
7015 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007016
7017 /// pointer_begin - First pointer type found;
7018 iterator pointer_begin() { return PointerTypes.begin(); }
7019
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007020 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007021 iterator pointer_end() { return PointerTypes.end(); }
7022
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007023 /// member_pointer_begin - First member pointer type found;
7024 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7025
7026 /// member_pointer_end - Past the last member pointer type found;
7027 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7028
Douglas Gregora11693b2008-11-12 17:17:38 +00007029 /// enumeration_begin - First enumeration type found;
7030 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7031
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007032 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007033 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007034
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007035 iterator vector_begin() { return VectorTypes.begin(); }
7036 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007037
7038 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7039 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007040 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007041};
7042
Craig Toppercd7b0332013-07-01 06:29:40 +00007043} // end anonymous namespace
7044
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007045/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007046/// the set of pointer types along with any more-qualified variants of
7047/// that type. For example, if @p Ty is "int const *", this routine
7048/// will add "int const *", "int const volatile *", "int const
7049/// restrict *", and "int const volatile restrict *" to the set of
7050/// pointer types. Returns true if the add of @p Ty itself succeeded,
7051/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007052///
7053/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007054bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007055BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7056 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007057
Douglas Gregora11693b2008-11-12 17:17:38 +00007058 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007059 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007060 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007061
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007062 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007063 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007064 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007065 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007066 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7067 PointeeTy = PTy->getPointeeType();
7068 buildObjCPtr = true;
7069 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007070 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007071 }
7072
Sebastian Redl4990a632009-11-18 20:39:26 +00007073 // Don't add qualified variants of arrays. For one, they're not allowed
7074 // (the qualifier would sink to the element type), and for another, the
7075 // only overload situation where it matters is subscript or pointer +- int,
7076 // and those shouldn't have qualifier variants anyway.
7077 if (PointeeTy->isArrayType())
7078 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007079
John McCall8ccfcb52009-09-24 19:53:00 +00007080 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007081 bool hasVolatile = VisibleQuals.hasVolatile();
7082 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007083
John McCall8ccfcb52009-09-24 19:53:00 +00007084 // Iterate through all strict supersets of BaseCVR.
7085 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7086 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007087 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007088 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007089
7090 // Skip over restrict if no restrict found anywhere in the types, or if
7091 // the type cannot be restrict-qualified.
7092 if ((CVR & Qualifiers::Restrict) &&
7093 (!hasRestrict ||
7094 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7095 continue;
7096
7097 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007098 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007099
7100 // Build qualified pointer type.
7101 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007102 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007103 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007104 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007105 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7106
7107 // Insert qualified pointer type.
7108 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007109 }
7110
7111 return true;
7112}
7113
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007114/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7115/// to the set of pointer types along with any more-qualified variants of
7116/// that type. For example, if @p Ty is "int const *", this routine
7117/// will add "int const *", "int const volatile *", "int const
7118/// restrict *", and "int const volatile restrict *" to the set of
7119/// pointer types. Returns true if the add of @p Ty itself succeeded,
7120/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007121///
7122/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007123bool
7124BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7125 QualType Ty) {
7126 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007127 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007128 return false;
7129
John McCall8ccfcb52009-09-24 19:53:00 +00007130 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7131 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007132
John McCall8ccfcb52009-09-24 19:53:00 +00007133 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007134 // Don't add qualified variants of arrays. For one, they're not allowed
7135 // (the qualifier would sink to the element type), and for another, the
7136 // only overload situation where it matters is subscript or pointer +- int,
7137 // and those shouldn't have qualifier variants anyway.
7138 if (PointeeTy->isArrayType())
7139 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007140 const Type *ClassTy = PointerTy->getClass();
7141
7142 // Iterate through all strict supersets of the pointee type's CVR
7143 // qualifiers.
7144 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7145 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7146 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007147
John McCall8ccfcb52009-09-24 19:53:00 +00007148 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007149 MemberPointerTypes.insert(
7150 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007151 }
7152
7153 return true;
7154}
7155
Douglas Gregora11693b2008-11-12 17:17:38 +00007156/// AddTypesConvertedFrom - Add each of the types to which the type @p
7157/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007158/// primarily interested in pointer types and enumeration types. We also
7159/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007160/// AllowUserConversions is true if we should look at the conversion
7161/// functions of a class type, and AllowExplicitConversions if we
7162/// should also include the explicit conversion functions of a class
7163/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007164void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007165BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007166 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007167 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007168 bool AllowExplicitConversions,
7169 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007170 // Only deal with canonical types.
7171 Ty = Context.getCanonicalType(Ty);
7172
7173 // Look through reference types; they aren't part of the type of an
7174 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007175 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007176 Ty = RefTy->getPointeeType();
7177
John McCall33ddac02011-01-19 10:06:00 +00007178 // If we're dealing with an array type, decay to the pointer.
7179 if (Ty->isArrayType())
7180 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7181
7182 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007183 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007184
Chandler Carruth00a38332010-12-13 01:44:01 +00007185 // Flag if we ever add a non-record type.
7186 const RecordType *TyRec = Ty->getAs<RecordType>();
7187 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7188
Chandler Carruth00a38332010-12-13 01:44:01 +00007189 // Flag if we encounter an arithmetic type.
7190 HasArithmeticOrEnumeralTypes =
7191 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7192
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007193 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7194 PointerTypes.insert(Ty);
7195 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007196 // Insert our type, and its more-qualified variants, into the set
7197 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007198 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007199 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007200 } else if (Ty->isMemberPointerType()) {
7201 // Member pointers are far easier, since the pointee can't be converted.
7202 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7203 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007204 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007205 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007206 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007207 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007208 // We treat vector types as arithmetic types in many contexts as an
7209 // extension.
7210 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007211 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007212 } else if (Ty->isNullPtrType()) {
7213 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007214 } else if (AllowUserConversions && TyRec) {
7215 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007216 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007217 return;
Mike Stump11289f42009-09-09 15:08:12 +00007218
Chandler Carruth00a38332010-12-13 01:44:01 +00007219 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007220 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007221 if (isa<UsingShadowDecl>(D))
7222 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007223
Chandler Carruth00a38332010-12-13 01:44:01 +00007224 // Skip conversion function templates; they don't tell us anything
7225 // about which builtin types we can convert to.
7226 if (isa<FunctionTemplateDecl>(D))
7227 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007228
Chandler Carruth00a38332010-12-13 01:44:01 +00007229 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7230 if (AllowExplicitConversions || !Conv->isExplicit()) {
7231 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7232 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007233 }
7234 }
7235 }
7236}
7237
Douglas Gregor84605ae2009-08-24 13:43:27 +00007238/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7239/// the volatile- and non-volatile-qualified assignment operators for the
7240/// given type to the candidate set.
7241static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7242 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007243 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007244 OverloadCandidateSet &CandidateSet) {
7245 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007246
Douglas Gregor84605ae2009-08-24 13:43:27 +00007247 // T& operator=(T&, T)
7248 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7249 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007250 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007251 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007252
Douglas Gregor84605ae2009-08-24 13:43:27 +00007253 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7254 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007255 ParamTypes[0]
7256 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007257 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007258 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007259 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007260 }
7261}
Mike Stump11289f42009-09-09 15:08:12 +00007262
Sebastian Redl1054fae2009-10-25 17:03:50 +00007263/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7264/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007265static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7266 Qualifiers VRQuals;
7267 const RecordType *TyRec;
7268 if (const MemberPointerType *RHSMPType =
7269 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007270 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007271 else
7272 TyRec = ArgExpr->getType()->getAs<RecordType>();
7273 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007274 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007275 VRQuals.addVolatile();
7276 VRQuals.addRestrict();
7277 return VRQuals;
7278 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007279
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007280 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007281 if (!ClassDecl->hasDefinition())
7282 return VRQuals;
7283
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007284 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007285 if (isa<UsingShadowDecl>(D))
7286 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7287 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007288 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7289 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7290 CanTy = ResTypeRef->getPointeeType();
7291 // Need to go down the pointer/mempointer chain and add qualifiers
7292 // as see them.
7293 bool done = false;
7294 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007295 if (CanTy.isRestrictQualified())
7296 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007297 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7298 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007299 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007300 CanTy->getAs<MemberPointerType>())
7301 CanTy = ResTypeMPtr->getPointeeType();
7302 else
7303 done = true;
7304 if (CanTy.isVolatileQualified())
7305 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007306 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7307 return VRQuals;
7308 }
7309 }
7310 }
7311 return VRQuals;
7312}
John McCall52872982010-11-13 05:51:15 +00007313
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007314namespace {
John McCall52872982010-11-13 05:51:15 +00007315
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007316/// \brief Helper class to manage the addition of builtin operator overload
7317/// candidates. It provides shared state and utility methods used throughout
7318/// the process, as well as a helper method to add each group of builtin
7319/// operator overloads from the standard to a candidate set.
7320class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007321 // Common instance state available to all overload candidate addition methods.
7322 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007323 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007324 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007325 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007326 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007327 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007328
Chandler Carruthc6586e52010-12-12 10:35:00 +00007329 // Define some constants used to index and iterate over the arithemetic types
7330 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007331 // The "promoted arithmetic types" are the arithmetic
7332 // types are that preserved by promotion (C++ [over.built]p2).
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007333 static const unsigned FirstIntegralType = 4;
7334 static const unsigned LastIntegralType = 21;
7335 static const unsigned FirstPromotedIntegralType = 4,
7336 LastPromotedIntegralType = 12;
John McCall52872982010-11-13 05:51:15 +00007337 static const unsigned FirstPromotedArithmeticType = 0,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007338 LastPromotedArithmeticType = 12;
7339 static const unsigned NumArithmeticTypes = 21;
John McCall52872982010-11-13 05:51:15 +00007340
Chandler Carruthc6586e52010-12-12 10:35:00 +00007341 /// \brief Get the canonical type for a given arithmetic type index.
7342 CanQualType getArithmeticType(unsigned index) {
7343 assert(index < NumArithmeticTypes);
7344 static CanQualType ASTContext::* const
7345 ArithmeticTypes[NumArithmeticTypes] = {
7346 // Start of promoted types.
7347 &ASTContext::FloatTy,
7348 &ASTContext::DoubleTy,
7349 &ASTContext::LongDoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007350 &ASTContext::Float128Ty,
John McCall52872982010-11-13 05:51:15 +00007351
Chandler Carruthc6586e52010-12-12 10:35:00 +00007352 // Start of integral types.
7353 &ASTContext::IntTy,
7354 &ASTContext::LongTy,
7355 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007356 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007357 &ASTContext::UnsignedIntTy,
7358 &ASTContext::UnsignedLongTy,
7359 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007360 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007361 // End of promoted types.
7362
7363 &ASTContext::BoolTy,
7364 &ASTContext::CharTy,
7365 &ASTContext::WCharTy,
7366 &ASTContext::Char16Ty,
7367 &ASTContext::Char32Ty,
7368 &ASTContext::SignedCharTy,
7369 &ASTContext::ShortTy,
7370 &ASTContext::UnsignedCharTy,
7371 &ASTContext::UnsignedShortTy,
7372 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007373 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007374 };
7375 return S.Context.*ArithmeticTypes[index];
7376 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007377
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007378 /// \brief Gets the canonical type resulting from the usual arithemetic
7379 /// converions for the given arithmetic types.
7380 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7381 // Accelerator table for performing the usual arithmetic conversions.
7382 // The rules are basically:
7383 // - if either is floating-point, use the wider floating-point
7384 // - if same signedness, use the higher rank
7385 // - if same size, use unsigned of the higher rank
7386 // - use the larger type
7387 // These rules, together with the axiom that higher ranks are
7388 // never smaller, are sufficient to precompute all of these results
7389 // *except* when dealing with signed types of higher rank.
7390 // (we could precompute SLL x UI for all known platforms, but it's
7391 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007392 // We assume that int128 has a higher rank than long long on all platforms.
George Burgess IVf23ce362016-04-29 21:32:53 +00007393 enum PromotedType : int8_t {
Richard Smith521ecc12012-06-10 08:00:26 +00007394 Dep=-1,
7395 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007396 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007397 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007398 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007399/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7400/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7401/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7402/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7403/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7404/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7405/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7406/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7407/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7408/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7409/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007410 };
7411
7412 assert(L < LastPromotedArithmeticType);
7413 assert(R < LastPromotedArithmeticType);
7414 int Idx = ConversionsTable[L][R];
7415
7416 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007417 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007418
7419 // Slow path: we need to compare widths.
7420 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007421 CanQualType LT = getArithmeticType(L),
7422 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007423 unsigned LW = S.Context.getIntWidth(LT),
7424 RW = S.Context.getIntWidth(RT);
7425
7426 // If they're different widths, use the signed type.
7427 if (LW > RW) return LT;
7428 else if (LW < RW) return RT;
7429
7430 // Otherwise, use the unsigned type of the signed type's rank.
7431 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7432 assert(L == SLL || R == SLL);
7433 return S.Context.UnsignedLongLongTy;
7434 }
7435
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007436 /// \brief Helper method to factor out the common pattern of adding overloads
7437 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007438 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007439 bool HasVolatile,
7440 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007441 QualType ParamTypes[2] = {
7442 S.Context.getLValueReferenceType(CandidateTy),
7443 S.Context.IntTy
7444 };
7445
7446 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007447 if (Args.size() == 1)
7448 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007449 else
Richard Smithe54c3072013-05-05 15:51:06 +00007450 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007451
7452 // Use a heuristic to reduce number of builtin candidates in the set:
7453 // add volatile version only if there are conversions to a volatile type.
7454 if (HasVolatile) {
7455 ParamTypes[0] =
7456 S.Context.getLValueReferenceType(
7457 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007458 if (Args.size() == 1)
7459 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007460 else
Richard Smithe54c3072013-05-05 15:51:06 +00007461 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007462 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007463
7464 // Add restrict version only if there are conversions to a restrict type
7465 // and our candidate type is a non-restrict-qualified pointer.
7466 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7467 !CandidateTy.isRestrictQualified()) {
7468 ParamTypes[0]
7469 = S.Context.getLValueReferenceType(
7470 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007471 if (Args.size() == 1)
7472 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007473 else
Richard Smithe54c3072013-05-05 15:51:06 +00007474 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007475
7476 if (HasVolatile) {
7477 ParamTypes[0]
7478 = S.Context.getLValueReferenceType(
7479 S.Context.getCVRQualifiedType(CandidateTy,
7480 (Qualifiers::Volatile |
7481 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007482 if (Args.size() == 1)
7483 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007484 else
Richard Smithe54c3072013-05-05 15:51:06 +00007485 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007486 }
7487 }
7488
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007489 }
7490
7491public:
7492 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007493 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007494 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007495 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007496 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007497 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007498 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007499 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007500 HasArithmeticOrEnumeralCandidateType(
7501 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007502 CandidateTypes(CandidateTypes),
7503 CandidateSet(CandidateSet) {
7504 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007505 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007506 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007507 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007508 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007509 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007510 assert(getArithmeticType(FirstPromotedArithmeticType)
7511 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007512 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007513 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007514 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007515 "Invalid last promoted arithmetic type");
7516 }
7517
7518 // C++ [over.built]p3:
7519 //
7520 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7521 // is either volatile or empty, there exist candidate operator
7522 // functions of the form
7523 //
7524 // VQ T& operator++(VQ T&);
7525 // T operator++(VQ T&, int);
7526 //
7527 // C++ [over.built]p4:
7528 //
7529 // For every pair (T, VQ), where T is an arithmetic type other
7530 // than bool, and VQ is either volatile or empty, there exist
7531 // candidate operator functions of the form
7532 //
7533 // VQ T& operator--(VQ T&);
7534 // T operator--(VQ T&, int);
7535 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007536 if (!HasArithmeticOrEnumeralCandidateType)
7537 return;
7538
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007539 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7540 Arith < NumArithmeticTypes; ++Arith) {
7541 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007542 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007543 VisibleTypeConversionsQuals.hasVolatile(),
7544 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007545 }
7546 }
7547
7548 // C++ [over.built]p5:
7549 //
7550 // For every pair (T, VQ), where T is a cv-qualified or
7551 // cv-unqualified object type, and VQ is either volatile or
7552 // empty, there exist candidate operator functions of the form
7553 //
7554 // T*VQ& operator++(T*VQ&);
7555 // T*VQ& operator--(T*VQ&);
7556 // T* operator++(T*VQ&, int);
7557 // T* operator--(T*VQ&, int);
7558 void addPlusPlusMinusMinusPointerOverloads() {
7559 for (BuiltinCandidateTypeSet::iterator
7560 Ptr = CandidateTypes[0].pointer_begin(),
7561 PtrEnd = CandidateTypes[0].pointer_end();
7562 Ptr != PtrEnd; ++Ptr) {
7563 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007564 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007565 continue;
7566
7567 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007568 (!(*Ptr).isVolatileQualified() &&
7569 VisibleTypeConversionsQuals.hasVolatile()),
7570 (!(*Ptr).isRestrictQualified() &&
7571 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007572 }
7573 }
7574
7575 // C++ [over.built]p6:
7576 // For every cv-qualified or cv-unqualified object type T, there
7577 // exist candidate operator functions of the form
7578 //
7579 // T& operator*(T*);
7580 //
7581 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007582 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007583 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007584 // T& operator*(T*);
7585 void addUnaryStarPointerOverloads() {
7586 for (BuiltinCandidateTypeSet::iterator
7587 Ptr = CandidateTypes[0].pointer_begin(),
7588 PtrEnd = CandidateTypes[0].pointer_end();
7589 Ptr != PtrEnd; ++Ptr) {
7590 QualType ParamTy = *Ptr;
7591 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007592 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7593 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007594
Douglas Gregor02824322011-01-26 19:30:28 +00007595 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7596 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7597 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007598
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007599 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007600 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007601 }
7602 }
7603
7604 // C++ [over.built]p9:
7605 // For every promoted arithmetic type T, there exist candidate
7606 // operator functions of the form
7607 //
7608 // T operator+(T);
7609 // T operator-(T);
7610 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007611 if (!HasArithmeticOrEnumeralCandidateType)
7612 return;
7613
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007614 for (unsigned Arith = FirstPromotedArithmeticType;
7615 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007616 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007617 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007618 }
7619
7620 // Extension: We also add these operators for vector types.
7621 for (BuiltinCandidateTypeSet::iterator
7622 Vec = CandidateTypes[0].vector_begin(),
7623 VecEnd = CandidateTypes[0].vector_end();
7624 Vec != VecEnd; ++Vec) {
7625 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007626 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007627 }
7628 }
7629
7630 // C++ [over.built]p8:
7631 // For every type T, there exist candidate operator functions of
7632 // the form
7633 //
7634 // T* operator+(T*);
7635 void addUnaryPlusPointerOverloads() {
7636 for (BuiltinCandidateTypeSet::iterator
7637 Ptr = CandidateTypes[0].pointer_begin(),
7638 PtrEnd = CandidateTypes[0].pointer_end();
7639 Ptr != PtrEnd; ++Ptr) {
7640 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007641 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007642 }
7643 }
7644
7645 // C++ [over.built]p10:
7646 // For every promoted integral type T, there exist candidate
7647 // operator functions of the form
7648 //
7649 // T operator~(T);
7650 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007651 if (!HasArithmeticOrEnumeralCandidateType)
7652 return;
7653
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007654 for (unsigned Int = FirstPromotedIntegralType;
7655 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007656 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007657 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007658 }
7659
7660 // Extension: We also add this operator for vector types.
7661 for (BuiltinCandidateTypeSet::iterator
7662 Vec = CandidateTypes[0].vector_begin(),
7663 VecEnd = CandidateTypes[0].vector_end();
7664 Vec != VecEnd; ++Vec) {
7665 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007666 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007667 }
7668 }
7669
7670 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007671 // For every pointer to member type T or type std::nullptr_t, there
7672 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007673 //
7674 // bool operator==(T,T);
7675 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007676 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007677 /// Set of (canonical) types that we've already handled.
7678 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7679
Richard Smithe54c3072013-05-05 15:51:06 +00007680 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007681 for (BuiltinCandidateTypeSet::iterator
7682 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7683 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7684 MemPtr != MemPtrEnd;
7685 ++MemPtr) {
7686 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007687 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007688 continue;
7689
7690 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007691 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007692 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007693
7694 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7695 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7696 if (AddedTypes.insert(NullPtrTy).second) {
7697 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7698 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7699 CandidateSet);
7700 }
7701 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007702 }
7703 }
7704
7705 // C++ [over.built]p15:
7706 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007707 // For every T, where T is an enumeration type or a pointer type,
7708 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007709 //
7710 // bool operator<(T, T);
7711 // bool operator>(T, T);
7712 // bool operator<=(T, T);
7713 // bool operator>=(T, T);
7714 // bool operator==(T, T);
7715 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007716 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007717 // C++ [over.match.oper]p3:
7718 // [...]the built-in candidates include all of the candidate operator
7719 // functions defined in 13.6 that, compared to the given operator, [...]
7720 // do not have the same parameter-type-list as any non-template non-member
7721 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007722 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007723 // Note that in practice, this only affects enumeration types because there
7724 // aren't any built-in candidates of record type, and a user-defined operator
7725 // must have an operand of record or enumeration type. Also, the only other
7726 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007727 // cannot be overloaded for enumeration types, so this is the only place
7728 // where we must suppress candidates like this.
7729 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7730 UserDefinedBinaryOperators;
7731
Richard Smithe54c3072013-05-05 15:51:06 +00007732 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007733 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7734 CandidateTypes[ArgIdx].enumeration_end()) {
7735 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7736 CEnd = CandidateSet.end();
7737 C != CEnd; ++C) {
7738 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7739 continue;
7740
Eli Friedman14f082b2012-09-18 21:52:24 +00007741 if (C->Function->isFunctionTemplateSpecialization())
7742 continue;
7743
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007744 QualType FirstParamType =
7745 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7746 QualType SecondParamType =
7747 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7748
7749 // Skip if either parameter isn't of enumeral type.
7750 if (!FirstParamType->isEnumeralType() ||
7751 !SecondParamType->isEnumeralType())
7752 continue;
7753
7754 // Add this operator to the set of known user-defined operators.
7755 UserDefinedBinaryOperators.insert(
7756 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7757 S.Context.getCanonicalType(SecondParamType)));
7758 }
7759 }
7760 }
7761
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007762 /// Set of (canonical) types that we've already handled.
7763 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7764
Richard Smithe54c3072013-05-05 15:51:06 +00007765 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007766 for (BuiltinCandidateTypeSet::iterator
7767 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7768 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7769 Ptr != PtrEnd; ++Ptr) {
7770 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007771 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007772 continue;
7773
7774 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007775 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007776 }
7777 for (BuiltinCandidateTypeSet::iterator
7778 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7779 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7780 Enum != EnumEnd; ++Enum) {
7781 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7782
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007783 // Don't add the same builtin candidate twice, or if a user defined
7784 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007785 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007786 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7787 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007788 continue;
7789
7790 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007791 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007792 }
7793 }
7794 }
7795
7796 // C++ [over.built]p13:
7797 //
7798 // For every cv-qualified or cv-unqualified object type T
7799 // there exist candidate operator functions of the form
7800 //
7801 // T* operator+(T*, ptrdiff_t);
7802 // T& operator[](T*, ptrdiff_t); [BELOW]
7803 // T* operator-(T*, ptrdiff_t);
7804 // T* operator+(ptrdiff_t, T*);
7805 // T& operator[](ptrdiff_t, T*); [BELOW]
7806 //
7807 // C++ [over.built]p14:
7808 //
7809 // For every T, where T is a pointer to object type, there
7810 // exist candidate operator functions of the form
7811 //
7812 // ptrdiff_t operator-(T, T);
7813 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7814 /// Set of (canonical) types that we've already handled.
7815 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7816
7817 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007818 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007819 S.Context.getPointerDiffType(),
7820 S.Context.getPointerDiffType(),
7821 };
7822 for (BuiltinCandidateTypeSet::iterator
7823 Ptr = CandidateTypes[Arg].pointer_begin(),
7824 PtrEnd = CandidateTypes[Arg].pointer_end();
7825 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007826 QualType PointeeTy = (*Ptr)->getPointeeType();
7827 if (!PointeeTy->isObjectType())
7828 continue;
7829
Eric Christopher9207a522015-08-21 16:24:01 +00007830 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007831 if (Arg == 0 || Op == OO_Plus) {
7832 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7833 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007834 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007835 }
7836 if (Op == OO_Minus) {
7837 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007838 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007839 continue;
7840
7841 QualType ParamTypes[2] = { *Ptr, *Ptr };
7842 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007843 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007844 }
7845 }
7846 }
7847 }
7848
7849 // C++ [over.built]p12:
7850 //
7851 // For every pair of promoted arithmetic types L and R, there
7852 // exist candidate operator functions of the form
7853 //
7854 // LR operator*(L, R);
7855 // LR operator/(L, R);
7856 // LR operator+(L, R);
7857 // LR operator-(L, R);
7858 // bool operator<(L, R);
7859 // bool operator>(L, R);
7860 // bool operator<=(L, R);
7861 // bool operator>=(L, R);
7862 // bool operator==(L, R);
7863 // bool operator!=(L, R);
7864 //
7865 // where LR is the result of the usual arithmetic conversions
7866 // between types L and R.
7867 //
7868 // C++ [over.built]p24:
7869 //
7870 // For every pair of promoted arithmetic types L and R, there exist
7871 // candidate operator functions of the form
7872 //
7873 // LR operator?(bool, L, R);
7874 //
7875 // where LR is the result of the usual arithmetic conversions
7876 // between types L and R.
7877 // Our candidates ignore the first parameter.
7878 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007879 if (!HasArithmeticOrEnumeralCandidateType)
7880 return;
7881
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007882 for (unsigned Left = FirstPromotedArithmeticType;
7883 Left < LastPromotedArithmeticType; ++Left) {
7884 for (unsigned Right = FirstPromotedArithmeticType;
7885 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007886 QualType LandR[2] = { getArithmeticType(Left),
7887 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007888 QualType Result =
7889 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007890 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007891 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007892 }
7893 }
7894
7895 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7896 // conditional operator for vector types.
7897 for (BuiltinCandidateTypeSet::iterator
7898 Vec1 = CandidateTypes[0].vector_begin(),
7899 Vec1End = CandidateTypes[0].vector_end();
7900 Vec1 != Vec1End; ++Vec1) {
7901 for (BuiltinCandidateTypeSet::iterator
7902 Vec2 = CandidateTypes[1].vector_begin(),
7903 Vec2End = CandidateTypes[1].vector_end();
7904 Vec2 != Vec2End; ++Vec2) {
7905 QualType LandR[2] = { *Vec1, *Vec2 };
7906 QualType Result = S.Context.BoolTy;
7907 if (!isComparison) {
7908 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7909 Result = *Vec1;
7910 else
7911 Result = *Vec2;
7912 }
7913
Richard Smithe54c3072013-05-05 15:51:06 +00007914 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007915 }
7916 }
7917 }
7918
7919 // C++ [over.built]p17:
7920 //
7921 // For every pair of promoted integral types L and R, there
7922 // exist candidate operator functions of the form
7923 //
7924 // LR operator%(L, R);
7925 // LR operator&(L, R);
7926 // LR operator^(L, R);
7927 // LR operator|(L, R);
7928 // L operator<<(L, R);
7929 // L operator>>(L, R);
7930 //
7931 // where LR is the result of the usual arithmetic conversions
7932 // between types L and R.
7933 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007934 if (!HasArithmeticOrEnumeralCandidateType)
7935 return;
7936
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007937 for (unsigned Left = FirstPromotedIntegralType;
7938 Left < LastPromotedIntegralType; ++Left) {
7939 for (unsigned Right = FirstPromotedIntegralType;
7940 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007941 QualType LandR[2] = { getArithmeticType(Left),
7942 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007943 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7944 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007945 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007946 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007947 }
7948 }
7949 }
7950
7951 // C++ [over.built]p20:
7952 //
7953 // For every pair (T, VQ), where T is an enumeration or
7954 // pointer to member type and VQ is either volatile or
7955 // empty, there exist candidate operator functions of the form
7956 //
7957 // VQ T& operator=(VQ T&, T);
7958 void addAssignmentMemberPointerOrEnumeralOverloads() {
7959 /// Set of (canonical) types that we've already handled.
7960 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7961
7962 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7963 for (BuiltinCandidateTypeSet::iterator
7964 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7965 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7966 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007967 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007968 continue;
7969
Richard Smithe54c3072013-05-05 15:51:06 +00007970 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007971 }
7972
7973 for (BuiltinCandidateTypeSet::iterator
7974 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7975 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7976 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007977 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007978 continue;
7979
Richard Smithe54c3072013-05-05 15:51:06 +00007980 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007981 }
7982 }
7983 }
7984
7985 // C++ [over.built]p19:
7986 //
7987 // For every pair (T, VQ), where T is any type and VQ is either
7988 // volatile or empty, there exist candidate operator functions
7989 // of the form
7990 //
7991 // T*VQ& operator=(T*VQ&, T*);
7992 //
7993 // C++ [over.built]p21:
7994 //
7995 // For every pair (T, VQ), where T is a cv-qualified or
7996 // cv-unqualified object type and VQ is either volatile or
7997 // empty, there exist candidate operator functions of the form
7998 //
7999 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8000 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8001 void addAssignmentPointerOverloads(bool isEqualOp) {
8002 /// Set of (canonical) types that we've already handled.
8003 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8004
8005 for (BuiltinCandidateTypeSet::iterator
8006 Ptr = CandidateTypes[0].pointer_begin(),
8007 PtrEnd = CandidateTypes[0].pointer_end();
8008 Ptr != PtrEnd; ++Ptr) {
8009 // If this is operator=, keep track of the builtin candidates we added.
8010 if (isEqualOp)
8011 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008012 else if (!(*Ptr)->getPointeeType()->isObjectType())
8013 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008014
8015 // non-volatile version
8016 QualType ParamTypes[2] = {
8017 S.Context.getLValueReferenceType(*Ptr),
8018 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8019 };
Richard Smithe54c3072013-05-05 15:51:06 +00008020 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008021 /*IsAssigmentOperator=*/ isEqualOp);
8022
Douglas Gregor5bee2582012-06-04 00:15:09 +00008023 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8024 VisibleTypeConversionsQuals.hasVolatile();
8025 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008026 // volatile version
8027 ParamTypes[0] =
8028 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008029 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008030 /*IsAssigmentOperator=*/isEqualOp);
8031 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008032
8033 if (!(*Ptr).isRestrictQualified() &&
8034 VisibleTypeConversionsQuals.hasRestrict()) {
8035 // restrict version
8036 ParamTypes[0]
8037 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008038 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008039 /*IsAssigmentOperator=*/isEqualOp);
8040
8041 if (NeedVolatile) {
8042 // volatile restrict version
8043 ParamTypes[0]
8044 = S.Context.getLValueReferenceType(
8045 S.Context.getCVRQualifiedType(*Ptr,
8046 (Qualifiers::Volatile |
8047 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008048 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008049 /*IsAssigmentOperator=*/isEqualOp);
8050 }
8051 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008052 }
8053
8054 if (isEqualOp) {
8055 for (BuiltinCandidateTypeSet::iterator
8056 Ptr = CandidateTypes[1].pointer_begin(),
8057 PtrEnd = CandidateTypes[1].pointer_end();
8058 Ptr != PtrEnd; ++Ptr) {
8059 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008060 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008061 continue;
8062
Chandler Carruth8e543b32010-12-12 08:17:55 +00008063 QualType ParamTypes[2] = {
8064 S.Context.getLValueReferenceType(*Ptr),
8065 *Ptr,
8066 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008067
8068 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00008069 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008070 /*IsAssigmentOperator=*/true);
8071
Douglas Gregor5bee2582012-06-04 00:15:09 +00008072 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8073 VisibleTypeConversionsQuals.hasVolatile();
8074 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008075 // volatile version
8076 ParamTypes[0] =
8077 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008078 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8079 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008080 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008081
8082 if (!(*Ptr).isRestrictQualified() &&
8083 VisibleTypeConversionsQuals.hasRestrict()) {
8084 // restrict version
8085 ParamTypes[0]
8086 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008087 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8088 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008089
8090 if (NeedVolatile) {
8091 // volatile restrict version
8092 ParamTypes[0]
8093 = S.Context.getLValueReferenceType(
8094 S.Context.getCVRQualifiedType(*Ptr,
8095 (Qualifiers::Volatile |
8096 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008097 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8098 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008099 }
8100 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008101 }
8102 }
8103 }
8104
8105 // C++ [over.built]p18:
8106 //
8107 // For every triple (L, VQ, R), where L is an arithmetic type,
8108 // VQ is either volatile or empty, and R is a promoted
8109 // arithmetic type, there exist candidate operator functions of
8110 // the form
8111 //
8112 // VQ L& operator=(VQ L&, R);
8113 // VQ L& operator*=(VQ L&, R);
8114 // VQ L& operator/=(VQ L&, R);
8115 // VQ L& operator+=(VQ L&, R);
8116 // VQ L& operator-=(VQ L&, R);
8117 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008118 if (!HasArithmeticOrEnumeralCandidateType)
8119 return;
8120
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008121 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8122 for (unsigned Right = FirstPromotedArithmeticType;
8123 Right < LastPromotedArithmeticType; ++Right) {
8124 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008125 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008126
8127 // Add this built-in operator as a candidate (VQ is empty).
8128 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008129 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008130 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008131 /*IsAssigmentOperator=*/isEqualOp);
8132
8133 // Add this built-in operator as a candidate (VQ is 'volatile').
8134 if (VisibleTypeConversionsQuals.hasVolatile()) {
8135 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008136 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008137 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008138 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008139 /*IsAssigmentOperator=*/isEqualOp);
8140 }
8141 }
8142 }
8143
8144 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8145 for (BuiltinCandidateTypeSet::iterator
8146 Vec1 = CandidateTypes[0].vector_begin(),
8147 Vec1End = CandidateTypes[0].vector_end();
8148 Vec1 != Vec1End; ++Vec1) {
8149 for (BuiltinCandidateTypeSet::iterator
8150 Vec2 = CandidateTypes[1].vector_begin(),
8151 Vec2End = CandidateTypes[1].vector_end();
8152 Vec2 != Vec2End; ++Vec2) {
8153 QualType ParamTypes[2];
8154 ParamTypes[1] = *Vec2;
8155 // Add this built-in operator as a candidate (VQ is empty).
8156 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008157 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008158 /*IsAssigmentOperator=*/isEqualOp);
8159
8160 // Add this built-in operator as a candidate (VQ is 'volatile').
8161 if (VisibleTypeConversionsQuals.hasVolatile()) {
8162 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8163 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008164 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008165 /*IsAssigmentOperator=*/isEqualOp);
8166 }
8167 }
8168 }
8169 }
8170
8171 // C++ [over.built]p22:
8172 //
8173 // For every triple (L, VQ, R), where L is an integral type, VQ
8174 // is either volatile or empty, and R is a promoted integral
8175 // type, there exist candidate operator functions of the form
8176 //
8177 // VQ L& operator%=(VQ L&, R);
8178 // VQ L& operator<<=(VQ L&, R);
8179 // VQ L& operator>>=(VQ L&, R);
8180 // VQ L& operator&=(VQ L&, R);
8181 // VQ L& operator^=(VQ L&, R);
8182 // VQ L& operator|=(VQ L&, R);
8183 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008184 if (!HasArithmeticOrEnumeralCandidateType)
8185 return;
8186
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008187 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8188 for (unsigned Right = FirstPromotedIntegralType;
8189 Right < LastPromotedIntegralType; ++Right) {
8190 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008191 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008192
8193 // Add this built-in operator as a candidate (VQ is empty).
8194 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008195 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008196 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008197 if (VisibleTypeConversionsQuals.hasVolatile()) {
8198 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008199 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008200 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8201 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008202 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008203 }
8204 }
8205 }
8206 }
8207
8208 // C++ [over.operator]p23:
8209 //
8210 // There also exist candidate operator functions of the form
8211 //
8212 // bool operator!(bool);
8213 // bool operator&&(bool, bool);
8214 // bool operator||(bool, bool);
8215 void addExclaimOverload() {
8216 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008217 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008218 /*IsAssignmentOperator=*/false,
8219 /*NumContextualBoolArguments=*/1);
8220 }
8221 void addAmpAmpOrPipePipeOverload() {
8222 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008223 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008224 /*IsAssignmentOperator=*/false,
8225 /*NumContextualBoolArguments=*/2);
8226 }
8227
8228 // C++ [over.built]p13:
8229 //
8230 // For every cv-qualified or cv-unqualified object type T there
8231 // exist candidate operator functions of the form
8232 //
8233 // T* operator+(T*, ptrdiff_t); [ABOVE]
8234 // T& operator[](T*, ptrdiff_t);
8235 // T* operator-(T*, ptrdiff_t); [ABOVE]
8236 // T* operator+(ptrdiff_t, T*); [ABOVE]
8237 // T& operator[](ptrdiff_t, T*);
8238 void addSubscriptOverloads() {
8239 for (BuiltinCandidateTypeSet::iterator
8240 Ptr = CandidateTypes[0].pointer_begin(),
8241 PtrEnd = CandidateTypes[0].pointer_end();
8242 Ptr != PtrEnd; ++Ptr) {
8243 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8244 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008245 if (!PointeeType->isObjectType())
8246 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008247
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008248 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8249
8250 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008251 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008252 }
8253
8254 for (BuiltinCandidateTypeSet::iterator
8255 Ptr = CandidateTypes[1].pointer_begin(),
8256 PtrEnd = CandidateTypes[1].pointer_end();
8257 Ptr != PtrEnd; ++Ptr) {
8258 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8259 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008260 if (!PointeeType->isObjectType())
8261 continue;
8262
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008263 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8264
8265 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008266 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008267 }
8268 }
8269
8270 // C++ [over.built]p11:
8271 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8272 // C1 is the same type as C2 or is a derived class of C2, T is an object
8273 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8274 // there exist candidate operator functions of the form
8275 //
8276 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8277 //
8278 // where CV12 is the union of CV1 and CV2.
8279 void addArrowStarOverloads() {
8280 for (BuiltinCandidateTypeSet::iterator
8281 Ptr = CandidateTypes[0].pointer_begin(),
8282 PtrEnd = CandidateTypes[0].pointer_end();
8283 Ptr != PtrEnd; ++Ptr) {
8284 QualType C1Ty = (*Ptr);
8285 QualType C1;
8286 QualifierCollector Q1;
8287 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8288 if (!isa<RecordType>(C1))
8289 continue;
8290 // heuristic to reduce number of builtin candidates in the set.
8291 // Add volatile/restrict version only if there are conversions to a
8292 // volatile/restrict type.
8293 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8294 continue;
8295 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8296 continue;
8297 for (BuiltinCandidateTypeSet::iterator
8298 MemPtr = CandidateTypes[1].member_pointer_begin(),
8299 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8300 MemPtr != MemPtrEnd; ++MemPtr) {
8301 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8302 QualType C2 = QualType(mptr->getClass(), 0);
8303 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008304 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008305 break;
8306 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8307 // build CV12 T&
8308 QualType T = mptr->getPointeeType();
8309 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8310 T.isVolatileQualified())
8311 continue;
8312 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8313 T.isRestrictQualified())
8314 continue;
8315 T = Q1.apply(S.Context, T);
8316 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008317 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008318 }
8319 }
8320 }
8321
8322 // Note that we don't consider the first argument, since it has been
8323 // contextually converted to bool long ago. The candidates below are
8324 // therefore added as binary.
8325 //
8326 // C++ [over.built]p25:
8327 // For every type T, where T is a pointer, pointer-to-member, or scoped
8328 // enumeration type, there exist candidate operator functions of the form
8329 //
8330 // T operator?(bool, T, T);
8331 //
8332 void addConditionalOperatorOverloads() {
8333 /// Set of (canonical) types that we've already handled.
8334 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8335
8336 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8337 for (BuiltinCandidateTypeSet::iterator
8338 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8339 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8340 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008341 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008342 continue;
8343
8344 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008345 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008346 }
8347
8348 for (BuiltinCandidateTypeSet::iterator
8349 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8350 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8351 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008352 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008353 continue;
8354
8355 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008356 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008357 }
8358
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008359 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008360 for (BuiltinCandidateTypeSet::iterator
8361 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8362 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8363 Enum != EnumEnd; ++Enum) {
8364 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8365 continue;
8366
David Blaikie82e95a32014-11-19 07:49:47 +00008367 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008368 continue;
8369
8370 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008371 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008372 }
8373 }
8374 }
8375 }
8376};
8377
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008378} // end anonymous namespace
8379
8380/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8381/// operator overloads to the candidate set (C++ [over.built]), based
8382/// on the operator @p Op and the arguments given. For example, if the
8383/// operator is a binary '+', this routine might add "int
8384/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008385void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8386 SourceLocation OpLoc,
8387 ArrayRef<Expr *> Args,
8388 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008389 // Find all of the types that the arguments can convert to, but only
8390 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008391 // that make use of these types. Also record whether we encounter non-record
8392 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008393 Qualifiers VisibleTypeConversionsQuals;
8394 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008395 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008396 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008397
8398 bool HasNonRecordCandidateType = false;
8399 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008400 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008401 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008402 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008403 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8404 OpLoc,
8405 true,
8406 (Op == OO_Exclaim ||
8407 Op == OO_AmpAmp ||
8408 Op == OO_PipePipe),
8409 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008410 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8411 CandidateTypes[ArgIdx].hasNonRecordTypes();
8412 HasArithmeticOrEnumeralCandidateType =
8413 HasArithmeticOrEnumeralCandidateType ||
8414 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008415 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008416
Chandler Carruth00a38332010-12-13 01:44:01 +00008417 // Exit early when no non-record types have been added to the candidate set
8418 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008419 //
8420 // We can't exit early for !, ||, or &&, since there we have always have
8421 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008422 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008423 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008424 return;
8425
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008426 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008427 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008428 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008429 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008430 CandidateTypes, CandidateSet);
8431
8432 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008433 switch (Op) {
8434 case OO_None:
8435 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008436 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008437
Chandler Carruth5184de02010-12-12 08:51:33 +00008438 case OO_New:
8439 case OO_Delete:
8440 case OO_Array_New:
8441 case OO_Array_Delete:
8442 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008443 llvm_unreachable(
8444 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008445
8446 case OO_Comma:
8447 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008448 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008449 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008450 // -- For the operator ',', the unary operator '&', the
8451 // operator '->', or the operator 'co_await', the
8452 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008453 break;
8454
8455 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008456 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008457 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008458 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008459
8460 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008461 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008462 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008463 } else {
8464 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8465 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8466 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008467 break;
8468
Chandler Carruth5184de02010-12-12 08:51:33 +00008469 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008470 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008471 OpBuilder.addUnaryStarPointerOverloads();
8472 else
8473 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8474 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008475
Chandler Carruth5184de02010-12-12 08:51:33 +00008476 case OO_Slash:
8477 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008478 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008479
8480 case OO_PlusPlus:
8481 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008482 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8483 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008484 break;
8485
Douglas Gregor84605ae2009-08-24 13:43:27 +00008486 case OO_EqualEqual:
8487 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008488 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008489 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008490
Douglas Gregora11693b2008-11-12 17:17:38 +00008491 case OO_Less:
8492 case OO_Greater:
8493 case OO_LessEqual:
8494 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008495 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008496 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8497 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008498
Douglas Gregora11693b2008-11-12 17:17:38 +00008499 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008500 case OO_Caret:
8501 case OO_Pipe:
8502 case OO_LessLess:
8503 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008504 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008505 break;
8506
Chandler Carruth5184de02010-12-12 08:51:33 +00008507 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008508 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008509 // C++ [over.match.oper]p3:
8510 // -- For the operator ',', the unary operator '&', or the
8511 // operator '->', the built-in candidates set is empty.
8512 break;
8513
8514 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8515 break;
8516
8517 case OO_Tilde:
8518 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8519 break;
8520
Douglas Gregora11693b2008-11-12 17:17:38 +00008521 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008522 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008523 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008524
8525 case OO_PlusEqual:
8526 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008527 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008528 // Fall through.
8529
8530 case OO_StarEqual:
8531 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008532 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008533 break;
8534
8535 case OO_PercentEqual:
8536 case OO_LessLessEqual:
8537 case OO_GreaterGreaterEqual:
8538 case OO_AmpEqual:
8539 case OO_CaretEqual:
8540 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008541 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008542 break;
8543
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008544 case OO_Exclaim:
8545 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008546 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008547
Douglas Gregora11693b2008-11-12 17:17:38 +00008548 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008549 case OO_PipePipe:
8550 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008551 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008552
8553 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008554 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008555 break;
8556
8557 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008558 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008559 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008560
8561 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008562 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008563 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8564 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008565 }
8566}
8567
Douglas Gregore254f902009-02-04 00:32:51 +00008568/// \brief Add function candidates found via argument-dependent lookup
8569/// to the set of overloading candidates.
8570///
8571/// This routine performs argument-dependent name lookup based on the
8572/// given function name (which may also be an operator name) and adds
8573/// all of the overload candidates found by ADL to the overload
8574/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008575void
Douglas Gregore254f902009-02-04 00:32:51 +00008576Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008577 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008578 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008579 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008580 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008581 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008582 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008583
John McCall91f61fc2010-01-26 06:04:06 +00008584 // FIXME: This approach for uniquing ADL results (and removing
8585 // redundant candidates from the set) relies on pointer-equality,
8586 // which means we need to key off the canonical decl. However,
8587 // always going back to the canonical decl might not get us the
8588 // right set of default arguments. What default arguments are
8589 // we supposed to consider on ADL candidates, anyway?
8590
Douglas Gregorcabea402009-09-22 15:41:20 +00008591 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008592 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008593
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008594 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008595 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8596 CandEnd = CandidateSet.end();
8597 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008598 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008599 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008600 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008601 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008602 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008603
8604 // For each of the ADL candidates we found, add it to the overload
8605 // set.
John McCall8fe68082010-01-26 07:16:45 +00008606 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008607 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008608 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008609 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008610 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008611
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008612 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8613 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008614 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008615 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008616 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008617 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008618 }
Douglas Gregore254f902009-02-04 00:32:51 +00008619}
8620
George Burgess IV3dc166912016-05-10 01:59:34 +00008621namespace {
8622enum class Comparison { Equal, Better, Worse };
8623}
8624
8625/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8626/// overload resolution.
8627///
8628/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8629/// Cand1's first N enable_if attributes have precisely the same conditions as
8630/// Cand2's first N enable_if attributes (where N = the number of enable_if
8631/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8632///
8633/// Note that you can have a pair of candidates such that Cand1's enable_if
8634/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8635/// worse than Cand1's.
8636static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8637 const FunctionDecl *Cand2) {
8638 // Common case: One (or both) decls don't have enable_if attrs.
8639 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8640 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8641 if (!Cand1Attr || !Cand2Attr) {
8642 if (Cand1Attr == Cand2Attr)
8643 return Comparison::Equal;
8644 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8645 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008646
8647 // FIXME: The next several lines are just
8648 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8649 // instead of reverse order which is how they're stored in the AST.
8650 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8651 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8652
George Burgess IV3dc166912016-05-10 01:59:34 +00008653 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8654 // has fewer enable_if attributes than Cand2.
8655 if (Cand1Attrs.size() < Cand2Attrs.size())
8656 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008657
8658 auto Cand1I = Cand1Attrs.begin();
8659 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8660 for (auto &Cand2A : Cand2Attrs) {
8661 Cand1ID.clear();
8662 Cand2ID.clear();
8663
8664 auto &Cand1A = *Cand1I++;
8665 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8666 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8667 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008668 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008669 }
8670
George Burgess IV3dc166912016-05-10 01:59:34 +00008671 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008672}
8673
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008674/// isBetterOverloadCandidate - Determines whether the first overload
8675/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008676bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8677 const OverloadCandidate &Cand2,
8678 SourceLocation Loc,
8679 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008680 // Define viable functions to be better candidates than non-viable
8681 // functions.
8682 if (!Cand2.Viable)
8683 return Cand1.Viable;
8684 else if (!Cand1.Viable)
8685 return false;
8686
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008687 // C++ [over.match.best]p1:
8688 //
8689 // -- if F is a static member function, ICS1(F) is defined such
8690 // that ICS1(F) is neither better nor worse than ICS1(G) for
8691 // any function G, and, symmetrically, ICS1(G) is neither
8692 // better nor worse than ICS1(F).
8693 unsigned StartArg = 0;
8694 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8695 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008696
George Burgess IVfbad5b22016-09-07 20:03:19 +00008697 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8698 // We don't allow incompatible pointer conversions in C++.
8699 if (!S.getLangOpts().CPlusPlus)
8700 return ICS.isStandard() &&
8701 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8702
8703 // The only ill-formed conversion we allow in C++ is the string literal to
8704 // char* conversion, which is only considered ill-formed after C++11.
8705 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8706 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8707 };
8708
8709 // Define functions that don't require ill-formed conversions for a given
8710 // argument to be better candidates than functions that do.
Renato Golindad96d62017-01-02 11:15:42 +00008711 unsigned NumArgs = Cand1.NumConversions;
8712 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
George Burgess IVfbad5b22016-09-07 20:03:19 +00008713 bool HasBetterConversion = false;
8714 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8715 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8716 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8717 if (Cand1Bad != Cand2Bad) {
8718 if (Cand1Bad)
8719 return false;
8720 HasBetterConversion = true;
8721 }
8722 }
8723
8724 if (HasBetterConversion)
8725 return true;
8726
Douglas Gregord3cb3562009-07-07 23:38:56 +00008727 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008728 // A viable function F1 is defined to be a better function than another
8729 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008730 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008731 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008732 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008733 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008734 Cand2.Conversions[ArgIdx])) {
8735 case ImplicitConversionSequence::Better:
8736 // Cand1 has a better conversion sequence.
8737 HasBetterConversion = true;
8738 break;
8739
8740 case ImplicitConversionSequence::Worse:
8741 // Cand1 can't be better than Cand2.
8742 return false;
8743
8744 case ImplicitConversionSequence::Indistinguishable:
8745 // Do nothing.
8746 break;
8747 }
8748 }
8749
Mike Stump11289f42009-09-09 15:08:12 +00008750 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008751 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008752 if (HasBetterConversion)
8753 return true;
8754
Douglas Gregora1f013e2008-11-07 22:36:19 +00008755 // -- the context is an initialization by user-defined conversion
8756 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8757 // from the return type of F1 to the destination type (i.e.,
8758 // the type of the entity being initialized) is a better
8759 // conversion sequence than the standard conversion sequence
8760 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008761 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008762 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008763 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008764 // First check whether we prefer one of the conversion functions over the
8765 // other. This only distinguishes the results in non-standard, extension
8766 // cases such as the conversion from a lambda closure type to a function
8767 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008768 ImplicitConversionSequence::CompareKind Result =
8769 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8770 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008771 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008772 Cand1.FinalConversion,
8773 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008774
Richard Smithec2748a2014-05-17 04:36:39 +00008775 if (Result != ImplicitConversionSequence::Indistinguishable)
8776 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008777
8778 // FIXME: Compare kind of reference binding if conversion functions
8779 // convert to a reference type used in direct reference binding, per
8780 // C++14 [over.match.best]p1 section 2 bullet 3.
8781 }
8782
8783 // -- F1 is a non-template function and F2 is a function template
8784 // specialization, or, if not that,
8785 bool Cand1IsSpecialization = Cand1.Function &&
8786 Cand1.Function->getPrimaryTemplate();
8787 bool Cand2IsSpecialization = Cand2.Function &&
8788 Cand2.Function->getPrimaryTemplate();
8789 if (Cand1IsSpecialization != Cand2IsSpecialization)
8790 return Cand2IsSpecialization;
8791
8792 // -- F1 and F2 are function template specializations, and the function
8793 // template for F1 is more specialized than the template for F2
8794 // according to the partial ordering rules described in 14.5.5.2, or,
8795 // if not that,
8796 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8797 if (FunctionTemplateDecl *BetterTemplate
8798 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8799 Cand2.Function->getPrimaryTemplate(),
8800 Loc,
8801 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8802 : TPOC_Call,
8803 Cand1.ExplicitCallArguments,
8804 Cand2.ExplicitCallArguments))
8805 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008806 }
8807
Richard Smith5179eb72016-06-28 19:03:57 +00008808 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8809 // A derived-class constructor beats an (inherited) base class constructor.
8810 bool Cand1IsInherited =
8811 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8812 bool Cand2IsInherited =
8813 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8814 if (Cand1IsInherited != Cand2IsInherited)
8815 return Cand2IsInherited;
8816 else if (Cand1IsInherited) {
8817 assert(Cand2IsInherited);
8818 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8819 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8820 if (Cand1Class->isDerivedFrom(Cand2Class))
8821 return true;
8822 if (Cand2Class->isDerivedFrom(Cand1Class))
8823 return false;
8824 // Inherited from sibling base classes: still ambiguous.
8825 }
8826
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008827 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00008828 if (Cand1.Function && Cand2.Function) {
8829 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8830 if (Cmp != Comparison::Equal)
8831 return Cmp == Comparison::Better;
8832 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008833
Justin Lebar25c4a812016-03-29 16:24:16 +00008834 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00008835 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8836 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8837 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8838 }
8839
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008840 bool HasPS1 = Cand1.Function != nullptr &&
8841 functionHasPassObjectSizeParams(Cand1.Function);
8842 bool HasPS2 = Cand2.Function != nullptr &&
8843 functionHasPassObjectSizeParams(Cand2.Function);
8844 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008845}
8846
Richard Smith2dbe4042015-11-04 19:26:32 +00008847/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008848/// name lookup and overload resolution. This applies when the same internal/no
8849/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008850/// the same header). In such a case, we don't consider the declarations to
8851/// declare the same entity, but we also don't want lookups with both
8852/// declarations visible to be ambiguous in some cases (this happens when using
8853/// a modularized libstdc++).
8854bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8855 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008856 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8857 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8858 if (!VA || !VB)
8859 return false;
8860
8861 // The declarations must be declaring the same name as an internal linkage
8862 // entity in different modules.
8863 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8864 VB->getDeclContext()->getRedeclContext()) ||
8865 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8866 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8867 VA->isExternallyVisible() || VB->isExternallyVisible())
8868 return false;
8869
8870 // Check that the declarations appear to be equivalent.
8871 //
8872 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8873 // For constants and functions, we should check the initializer or body is
8874 // the same. For non-constant variables, we shouldn't allow it at all.
8875 if (Context.hasSameType(VA->getType(), VB->getType()))
8876 return true;
8877
8878 // Enum constants within unnamed enumerations will have different types, but
8879 // may still be similar enough to be interchangeable for our purposes.
8880 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8881 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8882 // Only handle anonymous enums. If the enumerations were named and
8883 // equivalent, they would have been merged to the same type.
8884 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8885 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8886 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8887 !Context.hasSameType(EnumA->getIntegerType(),
8888 EnumB->getIntegerType()))
8889 return false;
8890 // Allow this only if the value is the same for both enumerators.
8891 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8892 }
8893 }
8894
8895 // Nothing else is sufficiently similar.
8896 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008897}
8898
8899void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8900 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8901 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8902
8903 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8904 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8905 << !M << (M ? M->getFullModuleName() : "");
8906
8907 for (auto *E : Equiv) {
8908 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8909 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8910 << !M << (M ? M->getFullModuleName() : "");
8911 }
Richard Smith896c66e2015-10-21 07:13:52 +00008912}
8913
Mike Stump11289f42009-09-09 15:08:12 +00008914/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008915/// within an overload candidate set.
8916///
James Dennettffad8b72012-06-22 08:10:18 +00008917/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008918/// which overload resolution occurs.
8919///
James Dennettffad8b72012-06-22 08:10:18 +00008920/// \param Best If overload resolution was successful or found a deleted
8921/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008922///
8923/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008924OverloadingResult
8925OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008926 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008927 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00008928 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8929 std::transform(begin(), end(), std::back_inserter(Candidates),
8930 [](OverloadCandidate &Cand) { return &Cand; });
8931
Justin Lebar66a2ab92016-08-10 00:40:43 +00008932 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8933 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00008934 // compilation mode only one call variant is viable. We need to
8935 // exclude non-viable overload candidates from consideration based
8936 // only on their host/device attributes. Specifically, if one
8937 // candidate call is WrongSide and the other is SameSide, we ignore
8938 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00008939 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00008940 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8941 bool ContainsSameSideCandidate =
8942 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8943 return Cand->Function &&
8944 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8945 Sema::CFP_SameSide;
8946 });
8947 if (ContainsSameSideCandidate) {
8948 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8949 return Cand->Function &&
8950 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8951 Sema::CFP_WrongSide;
8952 };
George Burgess IV8684b032017-01-04 19:16:29 +00008953 llvm::erase_if(Candidates, IsWrongSideCandidate);
Artem Belevich18609102016-02-12 18:29:18 +00008954 }
8955 }
8956
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008957 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008958 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00008959 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00008960 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008961 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008962 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008963 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008964
8965 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008966 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008967 return OR_No_Viable_Function;
8968
Richard Smith2dbe4042015-11-04 19:26:32 +00008969 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008970
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008971 // Make sure that this function is better than every other viable
8972 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00008973 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00008974 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008975 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008976 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008977 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008978 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8979 Cand->Function)) {
8980 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008981 continue;
8982 }
8983
John McCall5c32be02010-08-24 20:38:10 +00008984 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008985 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008986 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008987 }
Mike Stump11289f42009-09-09 15:08:12 +00008988
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008989 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008990 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008991 (Best->Function->isDeleted() ||
8992 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008993 return OR_Deleted;
8994
Richard Smith2dbe4042015-11-04 19:26:32 +00008995 if (!EquivalentCands.empty())
8996 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8997 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008998
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008999 return OR_Success;
9000}
9001
John McCall53262c92010-01-12 02:15:36 +00009002namespace {
9003
9004enum OverloadCandidateKind {
9005 oc_function,
9006 oc_method,
9007 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00009008 oc_function_template,
9009 oc_method_template,
9010 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00009011 oc_implicit_default_constructor,
9012 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009013 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009014 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009015 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00009016 oc_inherited_constructor,
9017 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00009018};
9019
George Burgess IVd66d37c2016-10-28 21:42:06 +00009020static OverloadCandidateKind
9021ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9022 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009023 bool isTemplate = false;
9024
9025 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9026 isTemplate = true;
9027 Description = S.getTemplateArgumentBindingsText(
9028 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9029 }
John McCallfd0b2f82010-01-06 09:43:14 +00009030
9031 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00009032 if (!Ctor->isImplicit()) {
9033 if (isa<ConstructorUsingShadowDecl>(Found))
9034 return isTemplate ? oc_inherited_constructor_template
9035 : oc_inherited_constructor;
9036 else
9037 return isTemplate ? oc_constructor_template : oc_constructor;
9038 }
Sebastian Redl08905022011-02-05 19:23:19 +00009039
Alexis Hunt119c10e2011-05-25 23:16:36 +00009040 if (Ctor->isDefaultConstructor())
9041 return oc_implicit_default_constructor;
9042
9043 if (Ctor->isMoveConstructor())
9044 return oc_implicit_move_constructor;
9045
9046 assert(Ctor->isCopyConstructor() &&
9047 "unexpected sort of implicit constructor");
9048 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00009049 }
9050
9051 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9052 // This actually gets spelled 'candidate function' for now, but
9053 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00009054 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00009055 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00009056
Alexis Hunt119c10e2011-05-25 23:16:36 +00009057 if (Meth->isMoveAssignmentOperator())
9058 return oc_implicit_move_assignment;
9059
Douglas Gregor12695102012-02-10 08:36:38 +00009060 if (Meth->isCopyAssignmentOperator())
9061 return oc_implicit_copy_assignment;
9062
9063 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9064 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00009065 }
9066
John McCalle1ac8d12010-01-13 00:25:19 +00009067 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00009068}
9069
Richard Smith5179eb72016-06-28 19:03:57 +00009070void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9071 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9072 // set.
9073 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9074 S.Diag(FoundDecl->getLocation(),
9075 diag::note_ovl_candidate_inherited_constructor)
9076 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009077}
9078
John McCall53262c92010-01-12 02:15:36 +00009079} // end anonymous namespace
9080
George Burgess IV5f21c712015-10-12 19:57:04 +00009081static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9082 const FunctionDecl *FD) {
9083 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9084 bool AlwaysTrue;
9085 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9086 return false;
9087 if (!AlwaysTrue)
9088 return false;
9089 }
9090 return true;
9091}
9092
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009093/// \brief Returns true if we can take the address of the function.
9094///
9095/// \param Complain - If true, we'll emit a diagnostic
9096/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9097/// we in overload resolution?
9098/// \param Loc - The location of the statement we're complaining about. Ignored
9099/// if we're not complaining, or if we're in overload resolution.
9100static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9101 bool Complain,
9102 bool InOverloadResolution,
9103 SourceLocation Loc) {
9104 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9105 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009106 if (InOverloadResolution)
9107 S.Diag(FD->getLocStart(),
9108 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9109 else
9110 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9111 }
9112 return false;
9113 }
9114
George Burgess IV21081362016-07-24 23:12:40 +00009115 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9116 return P->hasAttr<PassObjectSizeAttr>();
9117 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009118 if (I == FD->param_end())
9119 return true;
9120
9121 if (Complain) {
9122 // Add one to ParamNo because it's user-facing
9123 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9124 if (InOverloadResolution)
9125 S.Diag(FD->getLocation(),
9126 diag::note_ovl_candidate_has_pass_object_size_params)
9127 << ParamNo;
9128 else
9129 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9130 << FD << ParamNo;
9131 }
9132 return false;
9133}
9134
9135static bool checkAddressOfCandidateIsAvailable(Sema &S,
9136 const FunctionDecl *FD) {
9137 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9138 /*InOverloadResolution=*/true,
9139 /*Loc=*/SourceLocation());
9140}
9141
9142bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9143 bool Complain,
9144 SourceLocation Loc) {
9145 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9146 /*InOverloadResolution=*/false,
9147 Loc);
9148}
9149
John McCall53262c92010-01-12 02:15:36 +00009150// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009151void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9152 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009153 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9154 return;
9155
John McCalle1ac8d12010-01-13 00:25:19 +00009156 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009157 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009158 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00009159 << (unsigned) K << Fn << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009160
9161 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009162 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009163 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009164}
9165
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009166// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009167// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009168void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9169 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009170 assert(OverloadedExpr->getType() == Context.OverloadTy);
9171
9172 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9173 OverloadExpr *OvlExpr = Ovl.Expression;
9174
9175 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9176 IEnd = OvlExpr->decls_end();
9177 I != IEnd; ++I) {
9178 if (FunctionTemplateDecl *FunTmpl =
9179 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009180 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009181 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009182 } else if (FunctionDecl *Fun
9183 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009184 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009185 }
9186 }
9187}
9188
John McCall0d1da222010-01-12 00:44:57 +00009189/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9190/// "lead" diagnostic; it will be given two arguments, the source and
9191/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009192void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9193 Sema &S,
9194 SourceLocation CaretLoc,
9195 const PartialDiagnostic &PDiag) const {
9196 S.Diag(CaretLoc, PDiag)
9197 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009198 // FIXME: The note limiting machinery is borrowed from
9199 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9200 // refactoring here.
9201 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9202 unsigned CandsShown = 0;
9203 AmbiguousConversionSequence::const_iterator I, E;
9204 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9205 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9206 break;
9207 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009208 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009209 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009210 if (I != E)
9211 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009212}
9213
Richard Smith17c00b42014-11-12 01:24:00 +00009214static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009215 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009216 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9217 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009218 assert(Cand->Function && "for now, candidate must be a function");
9219 FunctionDecl *Fn = Cand->Function;
9220
9221 // There's a conversion slot for the object argument if this is a
9222 // non-constructor method. Note that 'I' corresponds the
9223 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009224 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009225 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009226 if (I == 0)
9227 isObjectArgument = true;
9228 else
9229 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009230 }
9231
John McCalle1ac8d12010-01-13 00:25:19 +00009232 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009233 OverloadCandidateKind FnKind =
9234 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009235
John McCall6a61b522010-01-13 09:16:55 +00009236 Expr *FromExpr = Conv.Bad.FromExpr;
9237 QualType FromTy = Conv.Bad.getFromType();
9238 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009239
John McCallfb7ad0f2010-02-02 02:42:52 +00009240 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009241 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009242 Expr *E = FromExpr->IgnoreParens();
9243 if (isa<UnaryOperator>(E))
9244 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009245 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009246
9247 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9248 << (unsigned) FnKind << FnDesc
9249 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9250 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009251 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009252 return;
9253 }
9254
John McCall6d174642010-01-23 08:10:49 +00009255 // Do some hand-waving analysis to see if the non-viability is due
9256 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009257 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9258 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9259 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9260 CToTy = RT->getPointeeType();
9261 else {
9262 // TODO: detect and diagnose the full richness of const mismatches.
9263 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009264 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9265 CFromTy = FromPT->getPointeeType();
9266 CToTy = ToPT->getPointeeType();
9267 }
John McCall47000992010-01-14 03:28:57 +00009268 }
9269
9270 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9271 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009272 Qualifiers FromQs = CFromTy.getQualifiers();
9273 Qualifiers ToQs = CToTy.getQualifiers();
9274
9275 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9276 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9277 << (unsigned) FnKind << FnDesc
9278 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9279 << FromTy
9280 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9281 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009282 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009283 return;
9284 }
9285
John McCall31168b02011-06-15 23:02:42 +00009286 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009287 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009288 << (unsigned) FnKind << FnDesc
9289 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9290 << FromTy
9291 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9292 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009293 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009294 return;
9295 }
9296
Douglas Gregoraec25842011-04-26 23:16:46 +00009297 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9298 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9299 << (unsigned) FnKind << FnDesc
9300 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9301 << FromTy
9302 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9303 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009304 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009305 return;
9306 }
9307
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009308 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9309 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9310 << (unsigned) FnKind << FnDesc
9311 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9312 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009313 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009314 return;
9315 }
9316
John McCall47000992010-01-14 03:28:57 +00009317 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9318 assert(CVR && "unexpected qualifiers mismatch");
9319
9320 if (isObjectArgument) {
9321 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9322 << (unsigned) FnKind << FnDesc
9323 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9324 << FromTy << (CVR - 1);
9325 } else {
9326 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9327 << (unsigned) FnKind << FnDesc
9328 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9329 << FromTy << (CVR - 1) << I+1;
9330 }
Richard Smith5179eb72016-06-28 19:03:57 +00009331 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009332 return;
9333 }
9334
Sebastian Redla72462c2011-09-24 17:48:32 +00009335 // Special diagnostic for failure to convert an initializer list, since
9336 // telling the user that it has type void is not useful.
9337 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9338 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9339 << (unsigned) FnKind << FnDesc
9340 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9341 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009342 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009343 return;
9344 }
9345
John McCall6d174642010-01-23 08:10:49 +00009346 // Diagnose references or pointers to incomplete types differently,
9347 // since it's far from impossible that the incompleteness triggered
9348 // the failure.
9349 QualType TempFromTy = FromTy.getNonReferenceType();
9350 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9351 TempFromTy = PTy->getPointeeType();
9352 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009353 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009354 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9355 << (unsigned) FnKind << FnDesc
9356 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009357 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9358 << (unsigned) (Cand->Fix.Kind);
9359
Richard Smith5179eb72016-06-28 19:03:57 +00009360 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009361 return;
9362 }
9363
Douglas Gregor56f2e342010-06-30 23:01:39 +00009364 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009365 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009366 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9367 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9368 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9369 FromPtrTy->getPointeeType()) &&
9370 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9371 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009372 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009373 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009374 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009375 }
9376 } else if (const ObjCObjectPointerType *FromPtrTy
9377 = FromTy->getAs<ObjCObjectPointerType>()) {
9378 if (const ObjCObjectPointerType *ToPtrTy
9379 = ToTy->getAs<ObjCObjectPointerType>())
9380 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9381 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9382 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9383 FromPtrTy->getPointeeType()) &&
9384 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009385 BaseToDerivedConversion = 2;
9386 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009387 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9388 !FromTy->isIncompleteType() &&
9389 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009390 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009391 BaseToDerivedConversion = 3;
9392 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9393 ToTy.getNonReferenceType().getCanonicalType() ==
9394 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009395 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9396 << (unsigned) FnKind << FnDesc
9397 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9398 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009399 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009400 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009401 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009403
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009404 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009405 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009406 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009407 << (unsigned) FnKind << FnDesc
9408 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009409 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009410 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009411 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009412 return;
9413 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009414
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009415 if (isa<ObjCObjectPointerType>(CFromTy) &&
9416 isa<PointerType>(CToTy)) {
9417 Qualifiers FromQs = CFromTy.getQualifiers();
9418 Qualifiers ToQs = CToTy.getQualifiers();
9419 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9420 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9421 << (unsigned) FnKind << FnDesc
9422 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9423 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009424 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009425 return;
9426 }
9427 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009428
9429 if (TakingCandidateAddress &&
9430 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9431 return;
9432
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009433 // Emit the generic diagnostic and, optionally, add the hints to it.
9434 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9435 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009436 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009437 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9438 << (unsigned) (Cand->Fix.Kind);
9439
9440 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009441 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9442 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009443 FDiag << *HI;
9444 S.Diag(Fn->getLocation(), FDiag);
9445
Richard Smith5179eb72016-06-28 19:03:57 +00009446 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009447}
9448
Larisse Voufo98b20f12013-07-19 23:00:19 +00009449/// Additional arity mismatch diagnosis specific to a function overload
9450/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9451/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009452static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9453 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009454 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009455 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009456
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009457 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009458 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009459 // right number of arguments, because only overloaded operators have
9460 // the weird behavior of overloading member and non-member functions.
9461 // Just don't report anything.
9462 if (Fn->isInvalidDecl() &&
9463 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009464 return true;
9465
9466 if (NumArgs < MinParams) {
9467 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9468 (Cand->FailureKind == ovl_fail_bad_deduction &&
9469 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9470 } else {
9471 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9472 (Cand->FailureKind == ovl_fail_bad_deduction &&
9473 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9474 }
9475
9476 return false;
9477}
9478
9479/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009480static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9481 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009482 assert(isa<FunctionDecl>(D) &&
9483 "The templated declaration should at least be a function"
9484 " when diagnosing bad template argument deduction due to too many"
9485 " or too few arguments");
9486
9487 FunctionDecl *Fn = cast<FunctionDecl>(D);
9488
9489 // TODO: treat calls to a missing default constructor as a special case
9490 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9491 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009492
John McCall6a61b522010-01-13 09:16:55 +00009493 // at least / at most / exactly
9494 unsigned mode, modeCount;
9495 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009496 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9497 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009498 mode = 0; // "at least"
9499 else
9500 mode = 2; // "exactly"
9501 modeCount = MinParams;
9502 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009503 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009504 mode = 1; // "at most"
9505 else
9506 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009507 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009508 }
9509
9510 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009511 OverloadCandidateKind FnKind =
9512 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009513
Richard Smith10ff50d2012-05-11 05:16:41 +00009514 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9515 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009516 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9517 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009518 else
9519 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009520 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9521 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009522 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009523}
9524
Larisse Voufo98b20f12013-07-19 23:00:19 +00009525/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009526static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9527 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009528 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009529 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009530}
Larisse Voufo47c08452013-07-19 22:53:23 +00009531
Richard Smith17c00b42014-11-12 01:24:00 +00009532static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009533 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9534 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009535 llvm_unreachable("Unsupported: Getting the described template declaration"
9536 " for bad deduction diagnosis");
9537}
9538
9539/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009540static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009541 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009542 unsigned NumArgs,
9543 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009544 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009545 NamedDecl *ParamD;
9546 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9547 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9548 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009549 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009550 case Sema::TDK_Success:
9551 llvm_unreachable("TDK_success while diagnosing bad deduction");
9552
9553 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009554 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009555 S.Diag(Templated->getLocation(),
9556 diag::note_ovl_candidate_incomplete_deduction)
9557 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009558 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009559 return;
9560 }
9561
John McCall42d7d192010-08-05 09:05:08 +00009562 case Sema::TDK_Underqualified: {
9563 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9564 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9565
Larisse Voufo98b20f12013-07-19 23:00:19 +00009566 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009567
9568 // Param will have been canonicalized, but it should just be a
9569 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009570 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009571 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009572 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009573 assert(S.Context.hasSameType(Param, NonCanonParam));
9574
9575 // Arg has also been canonicalized, but there's nothing we can do
9576 // about that. It also doesn't matter as much, because it won't
9577 // have any template parameters in it (because deduction isn't
9578 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009579 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009580
Larisse Voufo98b20f12013-07-19 23:00:19 +00009581 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9582 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009583 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009584 return;
9585 }
9586
9587 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009588 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009589 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009590 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009591 which = 0;
Richard Smith593d6a12016-12-23 01:30:39 +00009592 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9593 // Deduction might have failed because we deduced arguments of two
9594 // different types for a non-type template parameter.
9595 // FIXME: Use a different TDK value for this.
9596 QualType T1 =
9597 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9598 QualType T2 =
9599 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9600 if (!S.Context.hasSameType(T1, T2)) {
9601 S.Diag(Templated->getLocation(),
9602 diag::note_ovl_candidate_inconsistent_deduction_types)
9603 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9604 << *DeductionFailure.getSecondArg() << T2;
9605 MaybeEmitInheritedConstructorNote(S, Found);
9606 return;
9607 }
9608
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009609 which = 1;
Richard Smith593d6a12016-12-23 01:30:39 +00009610 } else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009611 which = 2;
9612 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009613
Larisse Voufo98b20f12013-07-19 23:00:19 +00009614 S.Diag(Templated->getLocation(),
9615 diag::note_ovl_candidate_inconsistent_deduction)
9616 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9617 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009618 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009619 return;
9620 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009621
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009622 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009623 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009624 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009625 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009626 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009627 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009628 else {
9629 int index = 0;
9630 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9631 index = TTP->getIndex();
9632 else if (NonTypeTemplateParmDecl *NTTP
9633 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9634 index = NTTP->getIndex();
9635 else
9636 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009637 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009638 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009639 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009640 }
Richard Smith5179eb72016-06-28 19:03:57 +00009641 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009642 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009643
Douglas Gregor02eb4832010-05-08 18:13:28 +00009644 case Sema::TDK_TooManyArguments:
9645 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009646 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009647 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009648
9649 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009650 S.Diag(Templated->getLocation(),
9651 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009652 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009653 return;
9654
9655 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009656 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009657 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009658 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009659 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009660 TemplateArgString = " ";
9661 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009662 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009663 }
9664
Richard Smith6f8d2c62012-05-09 05:17:00 +00009665 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009666 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009667 if (PDiag && PDiag->second.getDiagID() ==
9668 diag::err_typename_nested_not_found_enable_if) {
9669 // FIXME: Use the source range of the condition, and the fully-qualified
9670 // name of the enable_if template. These are both present in PDiag.
9671 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9672 << "'enable_if'" << TemplateArgString;
9673 return;
9674 }
9675
Richard Smith9ca64612012-05-07 09:03:25 +00009676 // Format the SFINAE diagnostic into the argument string.
9677 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9678 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009679 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009680 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009681 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009682 SFINAEArgString = ": ";
9683 R = SourceRange(PDiag->first, PDiag->first);
9684 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9685 }
9686
Larisse Voufo98b20f12013-07-19 23:00:19 +00009687 S.Diag(Templated->getLocation(),
9688 diag::note_ovl_candidate_substitution_failure)
9689 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009690 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009691 return;
9692 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009693
Richard Smithc92d2062017-01-05 23:02:44 +00009694 case Sema::TDK_DeducedMismatch:
9695 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +00009696 // Format the template argument list into the argument string.
9697 SmallString<128> TemplateArgString;
9698 if (TemplateArgumentList *Args =
9699 DeductionFailure.getTemplateArgumentList()) {
9700 TemplateArgString = " ";
9701 TemplateArgString += S.getTemplateArgumentBindingsText(
9702 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9703 }
9704
9705 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9706 << (*DeductionFailure.getCallArgIndex() + 1)
9707 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
Richard Smithc92d2062017-01-05 23:02:44 +00009708 << TemplateArgString
9709 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
Richard Smith9b534542015-12-31 02:02:54 +00009710 break;
9711 }
9712
Richard Trieue3732352013-04-08 21:11:40 +00009713 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009714 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009715 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9716 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009717 if (FirstTA.getKind() == TemplateArgument::Template &&
9718 SecondTA.getKind() == TemplateArgument::Template) {
9719 TemplateName FirstTN = FirstTA.getAsTemplate();
9720 TemplateName SecondTN = SecondTA.getAsTemplate();
9721 if (FirstTN.getKind() == TemplateName::Template &&
9722 SecondTN.getKind() == TemplateName::Template) {
9723 if (FirstTN.getAsTemplateDecl()->getName() ==
9724 SecondTN.getAsTemplateDecl()->getName()) {
9725 // FIXME: This fixes a bad diagnostic where both templates are named
9726 // the same. This particular case is a bit difficult since:
9727 // 1) It is passed as a string to the diagnostic printer.
9728 // 2) The diagnostic printer only attempts to find a better
9729 // name for types, not decls.
9730 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009731 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009732 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9733 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9734 return;
9735 }
9736 }
9737 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009738
9739 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9740 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9741 return;
9742
Faisal Vali2b391ab2013-09-26 19:54:12 +00009743 // FIXME: For generic lambda parameters, check if the function is a lambda
9744 // call operator, and if so, emit a prettier and more informative
9745 // diagnostic that mentions 'auto' and lambda in addition to
9746 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009747 S.Diag(Templated->getLocation(),
9748 diag::note_ovl_candidate_non_deduced_mismatch)
9749 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009750 return;
Richard Trieue3732352013-04-08 21:11:40 +00009751 }
John McCall8b9ed552010-02-01 18:53:26 +00009752 // TODO: diagnose these individually, then kill off
9753 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009754 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009755 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +00009756 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009757 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +00009758 case Sema::TDK_CUDATargetMismatch:
9759 S.Diag(Templated->getLocation(),
9760 diag::note_cuda_ovl_candidate_target_mismatch);
9761 return;
John McCall8b9ed552010-02-01 18:53:26 +00009762 }
9763}
9764
Larisse Voufo98b20f12013-07-19 23:00:19 +00009765/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009766static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009767 unsigned NumArgs,
9768 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009769 unsigned TDK = Cand->DeductionFailure.Result;
9770 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9771 if (CheckArityMismatch(S, Cand, NumArgs))
9772 return;
9773 }
Richard Smithc2bebe92016-05-11 20:37:46 +00009774 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009775 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009776}
9777
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009778/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009779static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009780 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9781 FunctionDecl *Callee = Cand->Function;
9782
9783 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9784 CalleeTarget = S.IdentifyCUDATarget(Callee);
9785
9786 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009787 OverloadCandidateKind FnKind =
9788 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009789
9790 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009791 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9792
9793 // This could be an implicit constructor for which we could not infer the
9794 // target due to a collsion. Diagnose that case.
9795 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9796 if (Meth != nullptr && Meth->isImplicit()) {
9797 CXXRecordDecl *ParentClass = Meth->getParent();
9798 Sema::CXXSpecialMember CSM;
9799
9800 switch (FnKind) {
9801 default:
9802 return;
9803 case oc_implicit_default_constructor:
9804 CSM = Sema::CXXDefaultConstructor;
9805 break;
9806 case oc_implicit_copy_constructor:
9807 CSM = Sema::CXXCopyConstructor;
9808 break;
9809 case oc_implicit_move_constructor:
9810 CSM = Sema::CXXMoveConstructor;
9811 break;
9812 case oc_implicit_copy_assignment:
9813 CSM = Sema::CXXCopyAssignment;
9814 break;
9815 case oc_implicit_move_assignment:
9816 CSM = Sema::CXXMoveAssignment;
9817 break;
9818 };
9819
9820 bool ConstRHS = false;
9821 if (Meth->getNumParams()) {
9822 if (const ReferenceType *RT =
9823 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9824 ConstRHS = RT->getPointeeType().isConstQualified();
9825 }
9826 }
9827
9828 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9829 /* ConstRHS */ ConstRHS,
9830 /* Diagnose */ true);
9831 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009832}
9833
Richard Smith17c00b42014-11-12 01:24:00 +00009834static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009835 FunctionDecl *Callee = Cand->Function;
9836 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9837
9838 S.Diag(Callee->getLocation(),
9839 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9840 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9841}
9842
Yaxun Liu5b746652016-12-18 05:18:55 +00009843static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
9844 FunctionDecl *Callee = Cand->Function;
9845
9846 S.Diag(Callee->getLocation(),
9847 diag::note_ovl_candidate_disabled_by_extension);
9848}
9849
John McCall8b9ed552010-02-01 18:53:26 +00009850/// Generates a 'note' diagnostic for an overload candidate. We've
9851/// already generated a primary error at the call site.
9852///
9853/// It really does need to be a single diagnostic with its caret
9854/// pointed at the candidate declaration. Yes, this creates some
9855/// major challenges of technical writing. Yes, this makes pointing
9856/// out problems with specific arguments quite awkward. It's still
9857/// better than generating twenty screens of text for every failed
9858/// overload.
9859///
9860/// It would be great to be able to express per-candidate problems
9861/// more richly for those diagnostic clients that cared, but we'd
9862/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009863static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009864 unsigned NumArgs,
9865 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009866 FunctionDecl *Fn = Cand->Function;
9867
John McCall12f97bc2010-01-08 04:41:39 +00009868 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009869 if (Cand->Viable && (Fn->isDeleted() ||
9870 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009871 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009872 OverloadCandidateKind FnKind =
9873 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009874
9875 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009876 << FnKind << FnDesc
9877 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009878 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCalld3224162010-01-08 00:58:21 +00009879 return;
John McCall12f97bc2010-01-08 04:41:39 +00009880 }
9881
John McCalle1ac8d12010-01-13 00:25:19 +00009882 // We don't really have anything else to say about viable candidates.
9883 if (Cand->Viable) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009884 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009885 return;
9886 }
John McCall0d1da222010-01-12 00:44:57 +00009887
John McCall6a61b522010-01-13 09:16:55 +00009888 switch (Cand->FailureKind) {
9889 case ovl_fail_too_many_arguments:
9890 case ovl_fail_too_few_arguments:
9891 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009892
John McCall6a61b522010-01-13 09:16:55 +00009893 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +00009894 return DiagnoseBadDeduction(S, Cand, NumArgs,
9895 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009896
John McCall578a1f82014-12-14 01:46:53 +00009897 case ovl_fail_illegal_constructor: {
9898 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9899 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009900 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +00009901 return;
9902 }
9903
John McCallfe796dd2010-01-23 05:17:32 +00009904 case ovl_fail_trivial_conversion:
9905 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009906 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +00009907 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009908
John McCall65eb8792010-02-25 01:37:24 +00009909 case ovl_fail_bad_conversion: {
9910 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Renato Golindad96d62017-01-02 11:15:42 +00009911 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009912 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009913 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009914
John McCall6a61b522010-01-13 09:16:55 +00009915 // FIXME: this currently happens when we're called from SemaInit
9916 // when user-conversion overload fails. Figure out how to handle
9917 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +00009918 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009919 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009920
9921 case ovl_fail_bad_target:
9922 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009923
9924 case ovl_fail_enable_if:
9925 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009926
Yaxun Liu5b746652016-12-18 05:18:55 +00009927 case ovl_fail_ext_disabled:
9928 return DiagnoseOpenCLExtensionDisabled(S, Cand);
9929
George Burgess IV7204ed92016-01-07 02:26:57 +00009930 case ovl_fail_addr_not_available: {
9931 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9932 (void)Available;
9933 assert(!Available);
9934 break;
9935 }
John McCall65eb8792010-02-25 01:37:24 +00009936 }
John McCalld3224162010-01-08 00:58:21 +00009937}
9938
Richard Smith17c00b42014-11-12 01:24:00 +00009939static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009940 // Desugar the type of the surrogate down to a function type,
9941 // retaining as many typedefs as possible while still showing
9942 // the function type (and, therefore, its parameter types).
9943 QualType FnType = Cand->Surrogate->getConversionType();
9944 bool isLValueReference = false;
9945 bool isRValueReference = false;
9946 bool isPointer = false;
9947 if (const LValueReferenceType *FnTypeRef =
9948 FnType->getAs<LValueReferenceType>()) {
9949 FnType = FnTypeRef->getPointeeType();
9950 isLValueReference = true;
9951 } else if (const RValueReferenceType *FnTypeRef =
9952 FnType->getAs<RValueReferenceType>()) {
9953 FnType = FnTypeRef->getPointeeType();
9954 isRValueReference = true;
9955 }
9956 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9957 FnType = FnTypePtr->getPointeeType();
9958 isPointer = true;
9959 }
9960 // Desugar down to a function type.
9961 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9962 // Reconstruct the pointer/reference as appropriate.
9963 if (isPointer) FnType = S.Context.getPointerType(FnType);
9964 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9965 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9966
9967 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9968 << FnType;
9969}
9970
Richard Smith17c00b42014-11-12 01:24:00 +00009971static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9972 SourceLocation OpLoc,
9973 OverloadCandidate *Cand) {
Renato Golindad96d62017-01-02 11:15:42 +00009974 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009975 std::string TypeStr("operator");
9976 TypeStr += Opc;
9977 TypeStr += "(";
9978 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Renato Golindad96d62017-01-02 11:15:42 +00009979 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009980 TypeStr += ")";
9981 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9982 } else {
9983 TypeStr += ", ";
9984 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9985 TypeStr += ")";
9986 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9987 }
9988}
9989
Richard Smith17c00b42014-11-12 01:24:00 +00009990static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9991 OverloadCandidate *Cand) {
Renato Golindad96d62017-01-02 11:15:42 +00009992 unsigned NoOperands = Cand->NumConversions;
9993 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9994 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009995 if (ICS.isBad()) break; // all meaningless after first invalid
9996 if (!ICS.isAmbiguous()) continue;
9997
Richard Smithc2bebe92016-05-11 20:37:46 +00009998 ICS.DiagnoseAmbiguousConversion(
9999 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +000010000 }
10001}
10002
Larisse Voufo98b20f12013-07-19 23:00:19 +000010003static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +000010004 if (Cand->Function)
10005 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010006 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010007 return Cand->Surrogate->getLocation();
10008 return SourceLocation();
10009}
10010
Larisse Voufo98b20f12013-07-19 23:00:19 +000010011static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010012 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010013 case Sema::TDK_Success:
Renato Golindad96d62017-01-02 11:15:42 +000010014 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010015
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010016 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010017 case Sema::TDK_Incomplete:
10018 return 1;
10019
10020 case Sema::TDK_Underqualified:
10021 case Sema::TDK_Inconsistent:
10022 return 2;
10023
10024 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010025 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +000010026 case Sema::TDK_DeducedMismatchNested:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010027 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010028 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010029 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010030 return 3;
10031
10032 case Sema::TDK_InstantiationDepth:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010033 return 4;
10034
10035 case Sema::TDK_InvalidExplicitArguments:
10036 return 5;
10037
10038 case Sema::TDK_TooManyArguments:
10039 case Sema::TDK_TooFewArguments:
10040 return 6;
10041 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010042 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010043}
10044
Richard Smith17c00b42014-11-12 01:24:00 +000010045namespace {
John McCallad2587a2010-01-12 00:48:53 +000010046struct CompareOverloadCandidatesForDisplay {
10047 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010048 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010049 size_t NumArgs;
10050
Richard Smith0f59cb32015-12-18 21:45:41 +000010051 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010052 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +000010053
10054 bool operator()(const OverloadCandidate *L,
10055 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010056 // Fast-path this check.
10057 if (L == R) return false;
10058
John McCall12f97bc2010-01-08 04:41:39 +000010059 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010060 if (L->Viable) {
10061 if (!R->Viable) return true;
10062
10063 // TODO: introduce a tri-valued comparison for overload
10064 // candidates. Would be more worthwhile if we had a sort
10065 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +000010066 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10067 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +000010068 } else if (R->Viable)
10069 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010070
John McCall3712d9e2010-01-15 23:32:50 +000010071 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010072
John McCall3712d9e2010-01-15 23:32:50 +000010073 // Criteria by which we can sort non-viable candidates:
10074 if (!L->Viable) {
10075 // 1. Arity mismatches come after other candidates.
10076 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010077 L->FailureKind == ovl_fail_too_few_arguments) {
10078 if (R->FailureKind == ovl_fail_too_many_arguments ||
10079 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010080 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10081 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10082 if (LDist == RDist) {
10083 if (L->FailureKind == R->FailureKind)
10084 // Sort non-surrogates before surrogates.
10085 return !L->IsSurrogate && R->IsSurrogate;
10086 // Sort candidates requiring fewer parameters than there were
10087 // arguments given after candidates requiring more parameters
10088 // than there were arguments given.
10089 return L->FailureKind == ovl_fail_too_many_arguments;
10090 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010091 return LDist < RDist;
10092 }
John McCall3712d9e2010-01-15 23:32:50 +000010093 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010094 }
John McCall3712d9e2010-01-15 23:32:50 +000010095 if (R->FailureKind == ovl_fail_too_many_arguments ||
10096 R->FailureKind == ovl_fail_too_few_arguments)
10097 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010098
John McCallfe796dd2010-01-23 05:17:32 +000010099 // 2. Bad conversions come first and are ordered by the number
10100 // of bad conversions and quality of good conversions.
10101 if (L->FailureKind == ovl_fail_bad_conversion) {
10102 if (R->FailureKind != ovl_fail_bad_conversion)
10103 return true;
10104
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010105 // The conversion that can be fixed with a smaller number of changes,
10106 // comes first.
10107 unsigned numLFixes = L->Fix.NumConversionsFixed;
10108 unsigned numRFixes = R->Fix.NumConversionsFixed;
10109 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10110 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010111 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010112 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010113 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010114
John McCallfe796dd2010-01-23 05:17:32 +000010115 // If there's any ordering between the defined conversions...
10116 // FIXME: this might not be transitive.
Renato Golindad96d62017-01-02 11:15:42 +000010117 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +000010118
10119 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010120 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Renato Golindad96d62017-01-02 11:15:42 +000010121 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010122 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010123 L->Conversions[I],
10124 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010125 case ImplicitConversionSequence::Better:
10126 leftBetter++;
10127 break;
10128
10129 case ImplicitConversionSequence::Worse:
10130 leftBetter--;
10131 break;
10132
10133 case ImplicitConversionSequence::Indistinguishable:
10134 break;
10135 }
10136 }
10137 if (leftBetter > 0) return true;
10138 if (leftBetter < 0) return false;
10139
10140 } else if (R->FailureKind == ovl_fail_bad_conversion)
10141 return false;
10142
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010143 if (L->FailureKind == ovl_fail_bad_deduction) {
10144 if (R->FailureKind != ovl_fail_bad_deduction)
10145 return true;
10146
10147 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10148 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010149 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010150 } else if (R->FailureKind == ovl_fail_bad_deduction)
10151 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010152
John McCall3712d9e2010-01-15 23:32:50 +000010153 // TODO: others?
10154 }
10155
10156 // Sort everything else by location.
10157 SourceLocation LLoc = GetLocationForCandidate(L);
10158 SourceLocation RLoc = GetLocationForCandidate(R);
10159
10160 // Put candidates without locations (e.g. builtins) at the end.
10161 if (LLoc.isInvalid()) return false;
10162 if (RLoc.isInvalid()) return true;
10163
10164 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010165 }
10166};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010167}
John McCall12f97bc2010-01-08 04:41:39 +000010168
John McCallfe796dd2010-01-23 05:17:32 +000010169/// CompleteNonViableCandidate - Normally, overload resolution only
Renato Golindad96d62017-01-02 11:15:42 +000010170/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010171static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10172 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010173 assert(!Cand->Viable);
10174
10175 // Don't do anything on failures other than bad conversion.
10176 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10177
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010178 // We only want the FixIts if all the arguments can be corrected.
10179 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010180 // Use a implicit copy initialization to check conversion fixes.
10181 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010182
Renato Golindad96d62017-01-02 11:15:42 +000010183 // Skip forward to the first bad conversion.
10184 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
10185 unsigned ConvCount = Cand->NumConversions;
10186 while (true) {
John McCallfe796dd2010-01-23 05:17:32 +000010187 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
Renato Golindad96d62017-01-02 11:15:42 +000010188 ConvIdx++;
10189 if (Cand->Conversions[ConvIdx - 1].isBad()) {
10190 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +000010191 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010192 }
John McCallfe796dd2010-01-23 05:17:32 +000010193 }
10194
Renato Golindad96d62017-01-02 11:15:42 +000010195 if (ConvIdx == ConvCount)
10196 return;
10197
10198 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10199 "remaining conversion is initialized?");
10200
Douglas Gregoradc7a702010-04-16 17:45:54 +000010201 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010202 // operation somehow.
10203 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010204
Renato Golindad96d62017-01-02 11:15:42 +000010205 const FunctionProtoType* Proto;
10206 unsigned ArgIdx = ConvIdx;
John McCallfe796dd2010-01-23 05:17:32 +000010207
10208 if (Cand->IsSurrogate) {
10209 QualType ConvType
10210 = Cand->Surrogate->getConversionType().getNonReferenceType();
10211 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10212 ConvType = ConvPtrType->getPointeeType();
10213 Proto = ConvType->getAs<FunctionProtoType>();
Renato Golindad96d62017-01-02 11:15:42 +000010214 ArgIdx--;
John McCallfe796dd2010-01-23 05:17:32 +000010215 } else if (Cand->Function) {
10216 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10217 if (isa<CXXMethodDecl>(Cand->Function) &&
10218 !isa<CXXConstructorDecl>(Cand->Function))
Renato Golindad96d62017-01-02 11:15:42 +000010219 ArgIdx--;
John McCallfe796dd2010-01-23 05:17:32 +000010220 } else {
10221 // Builtin binary operator with a bad first conversion.
10222 assert(ConvCount <= 3);
Renato Golindad96d62017-01-02 11:15:42 +000010223 for (; ConvIdx != ConvCount; ++ConvIdx)
10224 Cand->Conversions[ConvIdx]
10225 = TryCopyInitialization(S, Args[ConvIdx],
10226 Cand->BuiltinTypes.ParamTypes[ConvIdx],
10227 SuppressUserConversions,
10228 /*InOverloadResolution*/ true,
10229 /*AllowObjCWritebackConversion=*/
10230 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +000010231 return;
10232 }
10233
10234 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010235 unsigned NumParams = Proto->getNumParams();
Renato Golindad96d62017-01-02 11:15:42 +000010236 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10237 if (ArgIdx < NumParams) {
10238 Cand->Conversions[ConvIdx] = TryCopyInitialization(
10239 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10240 /*InOverloadResolution=*/true,
10241 /*AllowObjCWritebackConversion=*/
10242 S.getLangOpts().ObjCAutoRefCount);
10243 // Store the FixIt in the candidate if it exists.
10244 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10245 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10246 }
10247 else
John McCallfe796dd2010-01-23 05:17:32 +000010248 Cand->Conversions[ConvIdx].setEllipsis();
10249 }
10250}
10251
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010252/// PrintOverloadCandidates - When overload resolution fails, prints
10253/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010254/// set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010255void OverloadCandidateSet::NoteCandidates(
10256 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10257 StringRef Opc, SourceLocation OpLoc,
10258 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010259 // Sort the candidates by viability and position. Sorting directly would
10260 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010261 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010262 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10263 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010264 if (!Filter(*Cand))
10265 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010266 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010267 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010268 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010269 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010270 if (Cand->Function || Cand->IsSurrogate)
10271 Cands.push_back(Cand);
10272 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10273 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010274 }
10275 }
10276
John McCallad2587a2010-01-12 00:48:53 +000010277 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010278 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010279
John McCall0d1da222010-01-12 00:44:57 +000010280 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010281
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010282 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010283 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010284 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010285 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10286 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010287
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010288 // Set an arbitrary limit on the number of candidate functions we'll spam
10289 // the user with. FIXME: This limit should depend on details of the
10290 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010291 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010292 break;
10293 }
10294 ++CandsShown;
10295
John McCalld3224162010-01-08 00:58:21 +000010296 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010297 NoteFunctionCandidate(S, Cand, Args.size(),
10298 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010299 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010300 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010301 else {
10302 assert(Cand->Viable &&
10303 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010304 // Generally we only see ambiguities including viable builtin
10305 // operators if overload resolution got screwed up by an
10306 // ambiguous user-defined conversion.
10307 //
10308 // FIXME: It's quite possible for different conversions to see
10309 // different ambiguities, though.
10310 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010311 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010312 ReportedAmbiguousConversions = true;
10313 }
John McCalld3224162010-01-08 00:58:21 +000010314
John McCall0d1da222010-01-12 00:44:57 +000010315 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010316 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010317 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010318 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010319
10320 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010321 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010322}
10323
Larisse Voufo98b20f12013-07-19 23:00:19 +000010324static SourceLocation
10325GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10326 return Cand->Specialization ? Cand->Specialization->getLocation()
10327 : SourceLocation();
10328}
10329
Richard Smith17c00b42014-11-12 01:24:00 +000010330namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010331struct CompareTemplateSpecCandidatesForDisplay {
10332 Sema &S;
10333 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10334
10335 bool operator()(const TemplateSpecCandidate *L,
10336 const TemplateSpecCandidate *R) {
10337 // Fast-path this check.
10338 if (L == R)
10339 return false;
10340
10341 // Assuming that both candidates are not matches...
10342
10343 // Sort by the ranking of deduction failures.
10344 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10345 return RankDeductionFailure(L->DeductionFailure) <
10346 RankDeductionFailure(R->DeductionFailure);
10347
10348 // Sort everything else by location.
10349 SourceLocation LLoc = GetLocationForCandidate(L);
10350 SourceLocation RLoc = GetLocationForCandidate(R);
10351
10352 // Put candidates without locations (e.g. builtins) at the end.
10353 if (LLoc.isInvalid())
10354 return false;
10355 if (RLoc.isInvalid())
10356 return true;
10357
10358 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10359 }
10360};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010361}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010362
10363/// Diagnose a template argument deduction failure.
10364/// We are treating these failures as overload failures due to bad
10365/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010366void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10367 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010368 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010369 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010370}
10371
10372void TemplateSpecCandidateSet::destroyCandidates() {
10373 for (iterator i = begin(), e = end(); i != e; ++i) {
10374 i->DeductionFailure.Destroy();
10375 }
10376}
10377
10378void TemplateSpecCandidateSet::clear() {
10379 destroyCandidates();
10380 Candidates.clear();
10381}
10382
10383/// NoteCandidates - When no template specialization match is found, prints
10384/// diagnostic messages containing the non-matching specializations that form
10385/// the candidate set.
10386/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10387/// OCD == OCD_AllCandidates and Cand->Viable == false.
10388void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10389 // Sort the candidates by position (assuming no candidate is a match).
10390 // Sorting directly would be prohibitive, so we make a set of pointers
10391 // and sort those.
10392 SmallVector<TemplateSpecCandidate *, 32> Cands;
10393 Cands.reserve(size());
10394 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10395 if (Cand->Specialization)
10396 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010397 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010398 // in general, want to list every possible builtin candidate.
10399 }
10400
10401 std::sort(Cands.begin(), Cands.end(),
10402 CompareTemplateSpecCandidatesForDisplay(S));
10403
10404 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10405 // for generalization purposes (?).
10406 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10407
10408 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10409 unsigned CandsShown = 0;
10410 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10411 TemplateSpecCandidate *Cand = *I;
10412
10413 // Set an arbitrary limit on the number of candidates we'll spam
10414 // the user with. FIXME: This limit should depend on details of the
10415 // candidate list.
10416 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10417 break;
10418 ++CandsShown;
10419
10420 assert(Cand->Specialization &&
10421 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010422 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010423 }
10424
10425 if (I != E)
10426 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10427}
10428
Douglas Gregorb491ed32011-02-19 21:32:49 +000010429// [PossiblyAFunctionType] --> [Return]
10430// NonFunctionType --> NonFunctionType
10431// R (A) --> R(A)
10432// R (*)(A) --> R (A)
10433// R (&)(A) --> R (A)
10434// R (S::*)(A) --> R (A)
10435QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10436 QualType Ret = PossiblyAFunctionType;
10437 if (const PointerType *ToTypePtr =
10438 PossiblyAFunctionType->getAs<PointerType>())
10439 Ret = ToTypePtr->getPointeeType();
10440 else if (const ReferenceType *ToTypeRef =
10441 PossiblyAFunctionType->getAs<ReferenceType>())
10442 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010443 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010444 PossiblyAFunctionType->getAs<MemberPointerType>())
10445 Ret = MemTypePtr->getPointeeType();
10446 Ret =
10447 Context.getCanonicalType(Ret).getUnqualifiedType();
10448 return Ret;
10449}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010450
Richard Smith9095e5b2016-11-01 01:31:23 +000010451static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10452 bool Complain = true) {
10453 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10454 S.DeduceReturnType(FD, Loc, Complain))
10455 return true;
10456
10457 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10458 if (S.getLangOpts().CPlusPlus1z &&
10459 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10460 !S.ResolveExceptionSpec(Loc, FPT))
10461 return true;
10462
10463 return false;
10464}
10465
Richard Smith17c00b42014-11-12 01:24:00 +000010466namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010467// A helper class to help with address of function resolution
10468// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010469class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010470 Sema& S;
10471 Expr* SourceExpr;
10472 const QualType& TargetType;
10473 QualType TargetFunctionType; // Extracted function type from target type
10474
10475 bool Complain;
10476 //DeclAccessPair& ResultFunctionAccessPair;
10477 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010478
Douglas Gregorb491ed32011-02-19 21:32:49 +000010479 bool TargetTypeIsNonStaticMemberFunction;
10480 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010481 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010482 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010483
Douglas Gregorb491ed32011-02-19 21:32:49 +000010484 OverloadExpr::FindResult OvlExprInfo;
10485 OverloadExpr *OvlExpr;
10486 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010487 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010488 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010489
Douglas Gregorb491ed32011-02-19 21:32:49 +000010490public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010491 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10492 const QualType &TargetType, bool Complain)
10493 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10494 Complain(Complain), Context(S.getASTContext()),
10495 TargetTypeIsNonStaticMemberFunction(
10496 !!TargetType->getAs<MemberPointerType>()),
10497 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010498 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010499 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010500 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10501 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010502 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010503 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010504
David Majnemera4f7c7a2013-08-01 06:13:59 +000010505 if (TargetFunctionType->isFunctionType()) {
10506 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10507 if (!UME->isImplicitAccess() &&
10508 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10509 StaticMemberFunctionFromBoundPointer = true;
10510 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10511 DeclAccessPair dap;
10512 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10513 OvlExpr, false, &dap)) {
10514 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10515 if (!Method->isStatic()) {
10516 // If the target type is a non-function type and the function found
10517 // is a non-static member function, pretend as if that was the
10518 // target, it's the only possible type to end up with.
10519 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010520
David Majnemera4f7c7a2013-08-01 06:13:59 +000010521 // And skip adding the function if its not in the proper form.
10522 // We'll diagnose this due to an empty set of functions.
10523 if (!OvlExprInfo.HasFormOfMemberPointer)
10524 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010525 }
10526
David Majnemera4f7c7a2013-08-01 06:13:59 +000010527 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010528 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010529 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010530 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010531
10532 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010533 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010534
Douglas Gregorb491ed32011-02-19 21:32:49 +000010535 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10536 // C++ [over.over]p4:
10537 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010538 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010539 if (FoundNonTemplateFunction)
10540 EliminateAllTemplateMatches();
10541 else
10542 EliminateAllExceptMostSpecializedTemplate();
10543 }
10544 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010545
Justin Lebar25c4a812016-03-29 16:24:16 +000010546 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010547 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010548 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010549
10550 bool hasComplained() const { return HasComplained; }
10551
Douglas Gregorb491ed32011-02-19 21:32:49 +000010552private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010553 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10554 QualType Discard;
10555 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010556 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010557 }
10558
George Burgess IV6da4c202016-03-23 02:33:58 +000010559 /// \return true if A is considered a better overload candidate for the
10560 /// desired type than B.
10561 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10562 // If A doesn't have exactly the correct type, we don't want to classify it
10563 // as "better" than anything else. This way, the user is required to
10564 // disambiguate for us if there are multiple candidates and no exact match.
10565 return candidateHasExactlyCorrectType(A) &&
10566 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010567 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010568 }
10569
10570 /// \return true if we were able to eliminate all but one overload candidate,
10571 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010572 bool eliminiateSuboptimalOverloadCandidates() {
10573 // Same algorithm as overload resolution -- one pass to pick the "best",
10574 // another pass to be sure that nothing is better than the best.
10575 auto Best = Matches.begin();
10576 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10577 if (isBetterCandidate(I->second, Best->second))
10578 Best = I;
10579
10580 const FunctionDecl *BestFn = Best->second;
10581 auto IsBestOrInferiorToBest = [this, BestFn](
10582 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10583 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10584 };
10585
10586 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10587 // option, so we can potentially give the user a better error
10588 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10589 return false;
10590 Matches[0] = *Best;
10591 Matches.resize(1);
10592 return true;
10593 }
10594
Douglas Gregorb491ed32011-02-19 21:32:49 +000010595 bool isTargetTypeAFunction() const {
10596 return TargetFunctionType->isFunctionType();
10597 }
10598
10599 // [ToType] [Return]
10600
10601 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10602 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10603 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10604 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10605 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10606 }
10607
10608 // return true if any matching specializations were found
10609 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10610 const DeclAccessPair& CurAccessFunPair) {
10611 if (CXXMethodDecl *Method
10612 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10613 // Skip non-static function templates when converting to pointer, and
10614 // static when converting to member pointer.
10615 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10616 return false;
10617 }
10618 else if (TargetTypeIsNonStaticMemberFunction)
10619 return false;
10620
10621 // C++ [over.over]p2:
10622 // If the name is a function template, template argument deduction is
10623 // done (14.8.2.2), and if the argument deduction succeeds, the
10624 // resulting template argument list is used to generate a single
10625 // function template specialization, which is added to the set of
10626 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010627 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010628 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010629 if (Sema::TemplateDeductionResult Result
10630 = S.DeduceTemplateArguments(FunctionTemplate,
10631 &OvlExplicitTemplateArgs,
10632 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000010633 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010634 // Make a note of the failed deduction for diagnostics.
10635 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010636 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010637 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010638 return false;
10639 }
10640
Douglas Gregor19a41f12013-04-17 08:45:07 +000010641 // Template argument deduction ensures that we have an exact match or
10642 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010643 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010644 assert(S.isSameOrCompatibleFunctionType(
10645 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010646 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010647
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010648 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010649 return false;
10650
Douglas Gregorb491ed32011-02-19 21:32:49 +000010651 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10652 return true;
10653 }
10654
10655 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10656 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010657 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010658 // Skip non-static functions when converting to pointer, and static
10659 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010660 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10661 return false;
10662 }
10663 else if (TargetTypeIsNonStaticMemberFunction)
10664 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010665
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010666 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010667 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010668 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010669 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010670 return false;
10671
Richard Smith2a7d4812013-05-04 07:00:32 +000010672 // If any candidate has a placeholder return type, trigger its deduction
10673 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000010674 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10675 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000010676 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010677 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010678 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010679
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010680 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010681 return false;
10682
George Burgess IV6da4c202016-03-23 02:33:58 +000010683 // If we're in C, we need to support types that aren't exactly identical.
10684 if (!S.getLangOpts().CPlusPlus ||
10685 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010686 Matches.push_back(std::make_pair(
10687 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010688 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010689 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010690 }
Mike Stump11289f42009-09-09 15:08:12 +000010691 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010692
10693 return false;
10694 }
10695
10696 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10697 bool Ret = false;
10698
10699 // If the overload expression doesn't have the form of a pointer to
10700 // member, don't try to convert it to a pointer-to-member type.
10701 if (IsInvalidFormOfPointerToMemberFunction())
10702 return false;
10703
10704 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10705 E = OvlExpr->decls_end();
10706 I != E; ++I) {
10707 // Look through any using declarations to find the underlying function.
10708 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10709
10710 // C++ [over.over]p3:
10711 // Non-member functions and static member functions match
10712 // targets of type "pointer-to-function" or "reference-to-function."
10713 // Nonstatic member functions match targets of
10714 // type "pointer-to-member-function."
10715 // Note that according to DR 247, the containing class does not matter.
10716 if (FunctionTemplateDecl *FunctionTemplate
10717 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10718 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10719 Ret = true;
10720 }
10721 // If we have explicit template arguments supplied, skip non-templates.
10722 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10723 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10724 Ret = true;
10725 }
10726 assert(Ret || Matches.empty());
10727 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010728 }
10729
Douglas Gregorb491ed32011-02-19 21:32:49 +000010730 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010731 // [...] and any given function template specialization F1 is
10732 // eliminated if the set contains a second function template
10733 // specialization whose function template is more specialized
10734 // than the function template of F1 according to the partial
10735 // ordering rules of 14.5.5.2.
10736
10737 // The algorithm specified above is quadratic. We instead use a
10738 // two-pass algorithm (similar to the one used to identify the
10739 // best viable function in an overload set) that identifies the
10740 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010741
10742 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10743 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10744 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010745
Larisse Voufo98b20f12013-07-19 23:00:19 +000010746 // TODO: It looks like FailedCandidates does not serve much purpose
10747 // here, since the no_viable diagnostic has index 0.
10748 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010749 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010750 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000010751 S.PDiag(diag::err_addr_ovl_ambiguous)
10752 << Matches[0].second->getDeclName(),
10753 S.PDiag(diag::note_ovl_candidate)
10754 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010755 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010756
Douglas Gregorb491ed32011-02-19 21:32:49 +000010757 if (Result != MatchesCopy.end()) {
10758 // Make it the first and only element
10759 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10760 Matches[0].second = cast<FunctionDecl>(*Result);
10761 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010762 } else
10763 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010764 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010765
Douglas Gregorb491ed32011-02-19 21:32:49 +000010766 void EliminateAllTemplateMatches() {
10767 // [...] any function template specializations in the set are
10768 // eliminated if the set also contains a non-template function, [...]
10769 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010770 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010771 ++I;
10772 else {
10773 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010774 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010775 }
10776 }
10777 }
10778
Artem Belevich94a55e82015-09-22 17:22:59 +000010779 void EliminateSuboptimalCudaMatches() {
10780 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10781 }
10782
Douglas Gregorb491ed32011-02-19 21:32:49 +000010783public:
10784 void ComplainNoMatchesFound() const {
10785 assert(Matches.empty());
10786 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10787 << OvlExpr->getName() << TargetFunctionType
10788 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010789 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010790 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10791 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010792 else {
10793 // We have some deduction failure messages. Use them to diagnose
10794 // the function templates, and diagnose the non-template candidates
10795 // normally.
10796 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10797 IEnd = OvlExpr->decls_end();
10798 I != IEnd; ++I)
10799 if (FunctionDecl *Fun =
10800 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010801 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000010802 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010803 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010804 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10805 }
10806 }
10807
Douglas Gregorb491ed32011-02-19 21:32:49 +000010808 bool IsInvalidFormOfPointerToMemberFunction() const {
10809 return TargetTypeIsNonStaticMemberFunction &&
10810 !OvlExprInfo.HasFormOfMemberPointer;
10811 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010812
Douglas Gregorb491ed32011-02-19 21:32:49 +000010813 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10814 // TODO: Should we condition this on whether any functions might
10815 // have matched, or is it more appropriate to do that in callers?
10816 // TODO: a fixit wouldn't hurt.
10817 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10818 << TargetType << OvlExpr->getSourceRange();
10819 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010820
10821 bool IsStaticMemberFunctionFromBoundPointer() const {
10822 return StaticMemberFunctionFromBoundPointer;
10823 }
10824
10825 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10826 S.Diag(OvlExpr->getLocStart(),
10827 diag::err_invalid_form_pointer_member_function)
10828 << OvlExpr->getSourceRange();
10829 }
10830
Douglas Gregorb491ed32011-02-19 21:32:49 +000010831 void ComplainOfInvalidConversion() const {
10832 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10833 << OvlExpr->getName() << TargetType;
10834 }
10835
10836 void ComplainMultipleMatchesFound() const {
10837 assert(Matches.size() > 1);
10838 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10839 << OvlExpr->getName()
10840 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010841 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10842 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010843 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010844
10845 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10846
Douglas Gregorb491ed32011-02-19 21:32:49 +000010847 int getNumMatches() const { return Matches.size(); }
10848
10849 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010850 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010851 return Matches[0].second;
10852 }
10853
10854 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010855 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010856 return &Matches[0].first;
10857 }
10858};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010859}
Richard Smith17c00b42014-11-12 01:24:00 +000010860
Douglas Gregorb491ed32011-02-19 21:32:49 +000010861/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10862/// an overloaded function (C++ [over.over]), where @p From is an
10863/// expression with overloaded function type and @p ToType is the type
10864/// we're trying to resolve to. For example:
10865///
10866/// @code
10867/// int f(double);
10868/// int f(int);
10869///
10870/// int (*pfd)(double) = f; // selects f(double)
10871/// @endcode
10872///
10873/// This routine returns the resulting FunctionDecl if it could be
10874/// resolved, and NULL otherwise. When @p Complain is true, this
10875/// routine will emit diagnostics if there is an error.
10876FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010877Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10878 QualType TargetType,
10879 bool Complain,
10880 DeclAccessPair &FoundResult,
10881 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010882 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010883
10884 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10885 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010886 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010887 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010888 bool ShouldComplain = Complain && !Resolver.hasComplained();
10889 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010890 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10891 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10892 else
10893 Resolver.ComplainNoMatchesFound();
10894 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010895 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010896 Resolver.ComplainMultipleMatchesFound();
10897 else if (NumMatches == 1) {
10898 Fn = Resolver.getMatchingFunctionDecl();
10899 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000010900 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
10901 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010902 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010903 if (Complain) {
10904 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10905 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10906 else
10907 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10908 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010909 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010910
10911 if (pHadMultipleCandidates)
10912 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010913 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010914}
10915
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010916/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010917/// resolve that function to a single function that can have its address taken.
10918/// This will modify `Pair` iff it returns non-null.
10919///
10920/// This routine can only realistically succeed if all but one candidates in the
10921/// overload set for SrcExpr cannot have their addresses taken.
10922FunctionDecl *
10923Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10924 DeclAccessPair &Pair) {
10925 OverloadExpr::FindResult R = OverloadExpr::find(E);
10926 OverloadExpr *Ovl = R.Expression;
10927 FunctionDecl *Result = nullptr;
10928 DeclAccessPair DAP;
10929 // Don't use the AddressOfResolver because we're specifically looking for
10930 // cases where we have one overload candidate that lacks
10931 // enable_if/pass_object_size/...
10932 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10933 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10934 if (!FD)
10935 return nullptr;
10936
10937 if (!checkAddressOfFunctionIsAvailable(FD))
10938 continue;
10939
10940 // We have more than one result; quit.
10941 if (Result)
10942 return nullptr;
10943 DAP = I.getPair();
10944 Result = FD;
10945 }
10946
10947 if (Result)
10948 Pair = DAP;
10949 return Result;
10950}
10951
George Burgess IVbeca4a32016-06-08 00:34:22 +000010952/// \brief Given an overloaded function, tries to turn it into a non-overloaded
10953/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10954/// will perform access checks, diagnose the use of the resultant decl, and, if
10955/// necessary, perform a function-to-pointer decay.
10956///
10957/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10958/// Otherwise, returns true. This may emit diagnostics and return true.
10959bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10960 ExprResult &SrcExpr) {
10961 Expr *E = SrcExpr.get();
10962 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10963
10964 DeclAccessPair DAP;
10965 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10966 if (!Found)
10967 return false;
10968
10969 // Emitting multiple diagnostics for a function that is both inaccessible and
10970 // unavailable is consistent with our behavior elsewhere. So, always check
10971 // for both.
10972 DiagnoseUseOfDecl(Found, E->getExprLoc());
10973 CheckAddressOfMemberAccess(E, DAP);
10974 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10975 if (Fixed->getType()->isFunctionType())
10976 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10977 else
10978 SrcExpr = Fixed;
10979 return true;
10980}
10981
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010982/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010983/// resolve that overloaded function expression down to a single function.
10984///
10985/// This routine can only resolve template-ids that refer to a single function
10986/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010987/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010988/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010989///
10990/// If no template-ids are found, no diagnostics are emitted and NULL is
10991/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010992FunctionDecl *
10993Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10994 bool Complain,
10995 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010996 // C++ [over.over]p1:
10997 // [...] [Note: any redundant set of parentheses surrounding the
10998 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010999 // C++ [over.over]p1:
11000 // [...] The overloaded function name can be preceded by the &
11001 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011002
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011003 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000011004 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000011005 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011006
11007 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011008 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011009 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011010
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011011 // Look through all of the overloaded functions, searching for one
11012 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011013 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011014 for (UnresolvedSetIterator I = ovl->decls_begin(),
11015 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011016 // C++0x [temp.arg.explicit]p3:
11017 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011018 // where deduction is not done, if a template argument list is
11019 // specified and it, along with any default template arguments,
11020 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011021 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011022 FunctionTemplateDecl *FunctionTemplate
11023 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011024
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011025 // C++ [over.over]p2:
11026 // If the name is a function template, template argument deduction is
11027 // done (14.8.2.2), and if the argument deduction succeeds, the
11028 // resulting template argument list is used to generate a single
11029 // function template specialization, which is added to the set of
11030 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011031 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011032 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011033 if (TemplateDeductionResult Result
11034 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011035 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011036 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011037 // Make a note of the failed deduction for diagnostics.
11038 // TODO: Actually use the failed-deduction info?
11039 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011040 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011041 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011042 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011043 }
11044
John McCall0009fcc2011-04-26 20:42:42 +000011045 assert(Specialization && "no specialization and no error?");
11046
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011047 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011048 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011049 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011050 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11051 << ovl->getName();
11052 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011053 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011054 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011055 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011056
John McCall0009fcc2011-04-26 20:42:42 +000011057 Matched = Specialization;
11058 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011059 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011060
Richard Smith9095e5b2016-11-01 01:31:23 +000011061 if (Matched &&
11062 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011063 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011064
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011065 return Matched;
11066}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011067
Douglas Gregor1beec452011-03-12 01:48:56 +000011068
11069
11070
John McCall50a2c2c2011-10-11 23:14:30 +000011071// Resolve and fix an overloaded expression that can be resolved
11072// because it identifies a single function template specialization.
11073//
Douglas Gregor1beec452011-03-12 01:48:56 +000011074// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011075//
11076// Return true if it was logically possible to so resolve the
11077// expression, regardless of whether or not it succeeded. Always
11078// returns true if 'complain' is set.
11079bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11080 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000011081 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000011082 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011083 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011084 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011085
John McCall50a2c2c2011-10-11 23:14:30 +000011086 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011087
John McCall0009fcc2011-04-26 20:42:42 +000011088 DeclAccessPair found;
11089 ExprResult SingleFunctionExpression;
11090 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11091 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011092 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011093 SrcExpr = ExprError();
11094 return true;
11095 }
John McCall0009fcc2011-04-26 20:42:42 +000011096
11097 // It is only correct to resolve to an instance method if we're
11098 // resolving a form that's permitted to be a pointer to member.
11099 // Otherwise we'll end up making a bound member expression, which
11100 // is illegal in all the contexts we resolve like this.
11101 if (!ovl.HasFormOfMemberPointer &&
11102 isa<CXXMethodDecl>(fn) &&
11103 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011104 if (!complain) return false;
11105
11106 Diag(ovl.Expression->getExprLoc(),
11107 diag::err_bound_member_function)
11108 << 0 << ovl.Expression->getSourceRange();
11109
11110 // TODO: I believe we only end up here if there's a mix of
11111 // static and non-static candidates (otherwise the expression
11112 // would have 'bound member' type, not 'overload' type).
11113 // Ideally we would note which candidate was chosen and why
11114 // the static candidates were rejected.
11115 SrcExpr = ExprError();
11116 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011117 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011118
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011119 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011120 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011121 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011122
11123 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011124 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011125 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011126 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011127 if (SingleFunctionExpression.isInvalid()) {
11128 SrcExpr = ExprError();
11129 return true;
11130 }
11131 }
John McCall0009fcc2011-04-26 20:42:42 +000011132 }
11133
11134 if (!SingleFunctionExpression.isUsable()) {
11135 if (complain) {
11136 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11137 << ovl.Expression->getName()
11138 << DestTypeForComplaining
11139 << OpRangeForComplaining
11140 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011141 NoteAllOverloadCandidates(SrcExpr.get());
11142
11143 SrcExpr = ExprError();
11144 return true;
11145 }
11146
11147 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011148 }
11149
John McCall50a2c2c2011-10-11 23:14:30 +000011150 SrcExpr = SingleFunctionExpression;
11151 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011152}
11153
Douglas Gregorcabea402009-09-22 15:41:20 +000011154/// \brief Add a single candidate to the overload set.
11155static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011156 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011157 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011158 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011159 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011160 bool PartialOverloading,
11161 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011162 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011163 if (isa<UsingShadowDecl>(Callee))
11164 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11165
Douglas Gregorcabea402009-09-22 15:41:20 +000011166 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011167 if (ExplicitTemplateArgs) {
11168 assert(!KnownValid && "Explicit template arguments?");
11169 return;
11170 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011171 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11172 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011173 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011174 return;
John McCalld14a8642009-11-21 08:51:07 +000011175 }
11176
11177 if (FunctionTemplateDecl *FuncTemplate
11178 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011179 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011180 ExplicitTemplateArgs, Args, CandidateSet,
11181 /*SuppressUsedConversions=*/false,
11182 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011183 return;
11184 }
11185
Richard Smith95ce4f62011-06-26 22:19:54 +000011186 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011187}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011188
Douglas Gregorcabea402009-09-22 15:41:20 +000011189/// \brief Add the overload candidates named by callee and/or found by argument
11190/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011191void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011192 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011193 OverloadCandidateSet &CandidateSet,
11194 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011195
11196#ifndef NDEBUG
11197 // Verify that ArgumentDependentLookup is consistent with the rules
11198 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011199 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011200 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11201 // and let Y be the lookup set produced by argument dependent
11202 // lookup (defined as follows). If X contains
11203 //
11204 // -- a declaration of a class member, or
11205 //
11206 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011207 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011208 //
11209 // -- a declaration that is neither a function or a function
11210 // template
11211 //
11212 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011213
John McCall57500772009-12-16 12:17:52 +000011214 if (ULE->requiresADL()) {
11215 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11216 E = ULE->decls_end(); I != E; ++I) {
11217 assert(!(*I)->getDeclContext()->isRecord());
11218 assert(isa<UsingShadowDecl>(*I) ||
11219 !(*I)->getDeclContext()->isFunctionOrMethod());
11220 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011221 }
11222 }
11223#endif
11224
John McCall57500772009-12-16 12:17:52 +000011225 // It would be nice to avoid this copy.
11226 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011227 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011228 if (ULE->hasExplicitTemplateArgs()) {
11229 ULE->copyTemplateArgumentsInto(TABuffer);
11230 ExplicitTemplateArgs = &TABuffer;
11231 }
11232
11233 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11234 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011235 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11236 CandidateSet, PartialOverloading,
11237 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011238
John McCall57500772009-12-16 12:17:52 +000011239 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011240 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011241 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011242 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011243}
John McCalld681c392009-12-16 08:11:27 +000011244
Richard Smith0603bbb2013-06-12 22:56:54 +000011245/// Determine whether a declaration with the specified name could be moved into
11246/// a different namespace.
11247static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11248 switch (Name.getCXXOverloadedOperator()) {
11249 case OO_New: case OO_Array_New:
11250 case OO_Delete: case OO_Array_Delete:
11251 return false;
11252
11253 default:
11254 return true;
11255 }
11256}
11257
Richard Smith998a5912011-06-05 22:42:48 +000011258/// Attempt to recover from an ill-formed use of a non-dependent name in a
11259/// template, where the non-dependent name was declared after the template
11260/// was defined. This is common in code written for a compilers which do not
11261/// correctly implement two-stage name lookup.
11262///
11263/// Returns true if a viable candidate was found and a diagnostic was issued.
11264static bool
11265DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11266 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011267 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011268 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011269 ArrayRef<Expr *> Args,
11270 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000011271 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11272 return false;
11273
11274 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011275 if (DC->isTransparentContext())
11276 continue;
11277
Richard Smith998a5912011-06-05 22:42:48 +000011278 SemaRef.LookupQualifiedName(R, DC);
11279
11280 if (!R.empty()) {
11281 R.suppressDiagnostics();
11282
11283 if (isa<CXXRecordDecl>(DC)) {
11284 // Don't diagnose names we find in classes; we get much better
11285 // diagnostics for these from DiagnoseEmptyLookup.
11286 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011287 if (DoDiagnoseEmptyLookup)
11288 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011289 return false;
11290 }
11291
Richard Smith100b24a2014-04-17 01:52:14 +000011292 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011293 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11294 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011295 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011296 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011297
11298 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011299 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011300 // No viable functions. Don't bother the user with notes for functions
11301 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011302 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011303 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011304 }
Richard Smith998a5912011-06-05 22:42:48 +000011305
11306 // Find the namespaces where ADL would have looked, and suggest
11307 // declaring the function there instead.
11308 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11309 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011310 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011311 AssociatedNamespaces,
11312 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011313 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011314 if (canBeDeclaredInNamespace(R.getLookupName())) {
11315 DeclContext *Std = SemaRef.getStdNamespace();
11316 for (Sema::AssociatedNamespaceSet::iterator
11317 it = AssociatedNamespaces.begin(),
11318 end = AssociatedNamespaces.end(); it != end; ++it) {
11319 // Never suggest declaring a function within namespace 'std'.
11320 if (Std && Std->Encloses(*it))
11321 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011322
Richard Smith0603bbb2013-06-12 22:56:54 +000011323 // Never suggest declaring a function within a namespace with a
11324 // reserved name, like __gnu_cxx.
11325 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11326 if (NS &&
11327 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11328 continue;
11329
11330 SuggestedNamespaces.insert(*it);
11331 }
Richard Smith998a5912011-06-05 22:42:48 +000011332 }
11333
11334 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11335 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011336 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011337 SemaRef.Diag(Best->Function->getLocation(),
11338 diag::note_not_found_by_two_phase_lookup)
11339 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011340 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011341 SemaRef.Diag(Best->Function->getLocation(),
11342 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011343 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011344 } else {
11345 // FIXME: It would be useful to list the associated namespaces here,
11346 // but the diagnostics infrastructure doesn't provide a way to produce
11347 // a localized representation of a list of items.
11348 SemaRef.Diag(Best->Function->getLocation(),
11349 diag::note_not_found_by_two_phase_lookup)
11350 << R.getLookupName() << 2;
11351 }
11352
11353 // Try to recover by calling this function.
11354 return true;
11355 }
11356
11357 R.clear();
11358 }
11359
11360 return false;
11361}
11362
11363/// Attempt to recover from ill-formed use of a non-dependent operator in a
11364/// template, where the non-dependent operator was declared after the template
11365/// was defined.
11366///
11367/// Returns true if a viable candidate was found and a diagnostic was issued.
11368static bool
11369DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11370 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011371 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011372 DeclarationName OpName =
11373 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11374 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11375 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011376 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011377 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011378}
11379
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011380namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011381class BuildRecoveryCallExprRAII {
11382 Sema &SemaRef;
11383public:
11384 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11385 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11386 SemaRef.IsBuildingRecoveryCallExpr = true;
11387 }
11388
11389 ~BuildRecoveryCallExprRAII() {
11390 SemaRef.IsBuildingRecoveryCallExpr = false;
11391 }
11392};
11393
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011394}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011395
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011396static std::unique_ptr<CorrectionCandidateCallback>
11397MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11398 bool HasTemplateArgs, bool AllowTypoCorrection) {
11399 if (!AllowTypoCorrection)
11400 return llvm::make_unique<NoTypoCorrectionCCC>();
11401 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11402 HasTemplateArgs, ME);
11403}
11404
John McCalld681c392009-12-16 08:11:27 +000011405/// Attempts to recover from a call where no functions were found.
11406///
11407/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011408static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011409BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011410 UnresolvedLookupExpr *ULE,
11411 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011412 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011413 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011414 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011415 // Do not try to recover if it is already building a recovery call.
11416 // This stops infinite loops for template instantiations like
11417 //
11418 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11419 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11420 //
11421 if (SemaRef.IsBuildingRecoveryCallExpr)
11422 return ExprError();
11423 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011424
11425 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011426 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011427 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011428
John McCall57500772009-12-16 12:17:52 +000011429 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011430 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011431 if (ULE->hasExplicitTemplateArgs()) {
11432 ULE->copyTemplateArgumentsInto(TABuffer);
11433 ExplicitTemplateArgs = &TABuffer;
11434 }
11435
John McCalld681c392009-12-16 08:11:27 +000011436 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11437 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011438 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011439 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011440 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011441 ExplicitTemplateArgs, Args,
11442 &DoDiagnoseEmptyLookup) &&
11443 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11444 S, SS, R,
11445 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11446 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11447 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011448 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011449
John McCall57500772009-12-16 12:17:52 +000011450 assert(!R.empty() && "lookup results empty despite recovery");
11451
Richard Smith151c4562016-12-20 21:35:28 +000011452 // If recovery created an ambiguity, just bail out.
11453 if (R.isAmbiguous()) {
11454 R.suppressDiagnostics();
11455 return ExprError();
11456 }
11457
John McCall57500772009-12-16 12:17:52 +000011458 // Build an implicit member call if appropriate. Just drop the
11459 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011460 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011461 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011462 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11463 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011464 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011465 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011466 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011467 else
11468 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11469
11470 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011471 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011472
11473 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011474 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011475 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011476 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011477 MultiExprArg(Args.data(), Args.size()),
11478 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011479}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011480
Sam Panzer0f384432012-08-21 00:52:01 +000011481/// \brief Constructs and populates an OverloadedCandidateSet from
11482/// the given function.
11483/// \returns true when an the ExprResult output parameter has been set.
11484bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11485 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011486 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011487 SourceLocation RParenLoc,
11488 OverloadCandidateSet *CandidateSet,
11489 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011490#ifndef NDEBUG
11491 if (ULE->requiresADL()) {
11492 // To do ADL, we must have found an unqualified name.
11493 assert(!ULE->getQualifier() && "qualified name with ADL");
11494
11495 // We don't perform ADL for implicit declarations of builtins.
11496 // Verify that this was correctly set up.
11497 FunctionDecl *F;
11498 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11499 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11500 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011501 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011502
John McCall57500772009-12-16 12:17:52 +000011503 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011504 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011505 }
John McCall57500772009-12-16 12:17:52 +000011506#endif
11507
John McCall4124c492011-10-17 18:40:02 +000011508 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011509 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011510 *Result = ExprError();
11511 return true;
11512 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011513
John McCall57500772009-12-16 12:17:52 +000011514 // Add the functions denoted by the callee to the set of candidate
11515 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011516 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011517
Hans Wennborgb2747382015-06-12 21:23:23 +000011518 if (getLangOpts().MSVCCompat &&
11519 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011520 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11521
11522 OverloadCandidateSet::iterator Best;
11523 if (CandidateSet->empty() ||
11524 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11525 OR_No_Viable_Function) {
11526 // In Microsoft mode, if we are inside a template class member function then
11527 // create a type dependent CallExpr. The goal is to postpone name lookup
11528 // to instantiation time to be able to search into type dependent base
11529 // classes.
11530 CallExpr *CE = new (Context) CallExpr(
11531 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011532 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011533 CE->setValueDependent(true);
11534 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011535 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011536 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011537 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011538 }
John McCalld681c392009-12-16 08:11:27 +000011539
Hans Wennborg64937c62015-06-11 21:21:57 +000011540 if (CandidateSet->empty())
11541 return false;
11542
John McCall4124c492011-10-17 18:40:02 +000011543 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011544 return false;
11545}
John McCall4124c492011-10-17 18:40:02 +000011546
Sam Panzer0f384432012-08-21 00:52:01 +000011547/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11548/// the completed call expression. If overload resolution fails, emits
11549/// diagnostics and returns ExprError()
11550static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11551 UnresolvedLookupExpr *ULE,
11552 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011553 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011554 SourceLocation RParenLoc,
11555 Expr *ExecConfig,
11556 OverloadCandidateSet *CandidateSet,
11557 OverloadCandidateSet::iterator *Best,
11558 OverloadingResult OverloadResult,
11559 bool AllowTypoCorrection) {
11560 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011561 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011562 RParenLoc, /*EmptyLookup=*/true,
11563 AllowTypoCorrection);
11564
11565 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011566 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011567 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011568 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011569 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11570 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011571 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011572 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11573 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011574 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011575
Richard Smith998a5912011-06-05 22:42:48 +000011576 case OR_No_Viable_Function: {
11577 // Try to recover by looking for viable functions which the user might
11578 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011579 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011580 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011581 /*EmptyLookup=*/false,
11582 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011583 if (!Recovery.isInvalid())
11584 return Recovery;
11585
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011586 // If the user passes in a function that we can't take the address of, we
11587 // generally end up emitting really bad error messages. Here, we attempt to
11588 // emit better ones.
11589 for (const Expr *Arg : Args) {
11590 if (!Arg->getType()->isFunctionType())
11591 continue;
11592 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11593 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11594 if (FD &&
11595 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11596 Arg->getExprLoc()))
11597 return ExprError();
11598 }
11599 }
11600
11601 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11602 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011603 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011604 break;
Richard Smith998a5912011-06-05 22:42:48 +000011605 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011606
11607 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011608 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011609 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011610 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011611 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011612
Sam Panzer0f384432012-08-21 00:52:01 +000011613 case OR_Deleted: {
11614 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11615 << (*Best)->Function->isDeleted()
11616 << ULE->getName()
11617 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11618 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011619 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011620
Sam Panzer0f384432012-08-21 00:52:01 +000011621 // We emitted an error for the unvailable/deleted function call but keep
11622 // the call in the AST.
11623 FunctionDecl *FDecl = (*Best)->Function;
11624 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011625 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11626 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011627 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011628 }
11629
Douglas Gregorb412e172010-07-25 18:17:45 +000011630 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011631 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011632}
11633
George Burgess IV7204ed92016-01-07 02:26:57 +000011634static void markUnaddressableCandidatesUnviable(Sema &S,
11635 OverloadCandidateSet &CS) {
11636 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11637 if (I->Viable &&
11638 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11639 I->Viable = false;
11640 I->FailureKind = ovl_fail_addr_not_available;
11641 }
11642 }
11643}
11644
Sam Panzer0f384432012-08-21 00:52:01 +000011645/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11646/// (which eventually refers to the declaration Func) and the call
11647/// arguments Args/NumArgs, attempt to resolve the function call down
11648/// to a specific function. If overload resolution succeeds, returns
11649/// the call expression produced by overload resolution.
11650/// Otherwise, emits diagnostics and returns ExprError.
11651ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11652 UnresolvedLookupExpr *ULE,
11653 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011654 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011655 SourceLocation RParenLoc,
11656 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011657 bool AllowTypoCorrection,
11658 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011659 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11660 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011661 ExprResult result;
11662
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011663 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11664 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011665 return result;
11666
George Burgess IV7204ed92016-01-07 02:26:57 +000011667 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11668 // functions that aren't addressible are considered unviable.
11669 if (CalleesAddressIsTaken)
11670 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11671
Sam Panzer0f384432012-08-21 00:52:01 +000011672 OverloadCandidateSet::iterator Best;
11673 OverloadingResult OverloadResult =
11674 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11675
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011676 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011677 RParenLoc, ExecConfig, &CandidateSet,
11678 &Best, OverloadResult,
11679 AllowTypoCorrection);
11680}
11681
John McCall4c4c1df2010-01-26 03:27:55 +000011682static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011683 return Functions.size() > 1 ||
11684 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11685}
11686
Douglas Gregor084d8552009-03-13 23:49:33 +000011687/// \brief Create a unary operation that may resolve to an overloaded
11688/// operator.
11689///
11690/// \param OpLoc The location of the operator itself (e.g., '*').
11691///
Craig Toppera92ffb02015-12-10 08:51:49 +000011692/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011693///
James Dennett18348b62012-06-22 08:52:37 +000011694/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011695/// considered by overload resolution. The caller needs to build this
11696/// set based on the context using, e.g.,
11697/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11698/// set should not contain any member functions; those will be added
11699/// by CreateOverloadedUnaryOp().
11700///
James Dennett91738ff2012-06-22 10:32:46 +000011701/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011702ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011703Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011704 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011705 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011706 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11707 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11708 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011709 // TODO: provide better source location info.
11710 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011711
John McCall4124c492011-10-17 18:40:02 +000011712 if (checkPlaceholderForOverload(*this, Input))
11713 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011714
Craig Topperc3ec1492014-05-26 06:22:03 +000011715 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011716 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011717
Douglas Gregor084d8552009-03-13 23:49:33 +000011718 // For post-increment and post-decrement, add the implicit '0' as
11719 // the second argument, so that we know this is a post-increment or
11720 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011721 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011722 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011723 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11724 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011725 NumArgs = 2;
11726 }
11727
Richard Smithe54c3072013-05-05 15:51:06 +000011728 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11729
Douglas Gregor084d8552009-03-13 23:49:33 +000011730 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011731 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011732 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11733 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011734
Craig Topperc3ec1492014-05-26 06:22:03 +000011735 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011736 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011737 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011738 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011739 /*ADL*/ true, IsOverloaded(Fns),
11740 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011741 return new (Context)
11742 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11743 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011744 }
11745
11746 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011747 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011748
11749 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011750 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011751
11752 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011753 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011754
John McCall4c4c1df2010-01-26 03:27:55 +000011755 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011756 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011757 /*ExplicitTemplateArgs*/nullptr,
11758 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011759
Douglas Gregor084d8552009-03-13 23:49:33 +000011760 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011761 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011762
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011763 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11764
Douglas Gregor084d8552009-03-13 23:49:33 +000011765 // Perform overload resolution.
11766 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011767 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011768 case OR_Success: {
11769 // We found a built-in operator or an overloaded operator.
11770 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011771
Douglas Gregor084d8552009-03-13 23:49:33 +000011772 if (FnDecl) {
11773 // We matched an overloaded operator. Build a call to that
11774 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011775
Douglas Gregor084d8552009-03-13 23:49:33 +000011776 // Convert the arguments.
11777 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011778 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011779
John Wiegley01296292011-04-08 18:41:53 +000011780 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011781 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011782 Best->FoundDecl, Method);
11783 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011784 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011785 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011786 } else {
11787 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011788 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011789 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011790 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011791 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011792 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011793 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011794 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011795 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011796 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011797 }
11798
Douglas Gregor084d8552009-03-13 23:49:33 +000011799 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011800 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011801 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011802 if (FnExpr.isInvalid())
11803 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011804
Richard Smithc1564702013-11-15 02:58:23 +000011805 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011806 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011807 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11808 ResultTy = ResultTy.getNonLValueExprType(Context);
11809
Eli Friedman030eee42009-11-18 03:58:17 +000011810 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011811 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011812 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011813 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011814
Alp Toker314cc812014-01-25 16:55:45 +000011815 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011816 return ExprError();
11817
John McCallb268a282010-08-23 23:25:46 +000011818 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011819 } else {
11820 // We matched a built-in operator. Convert the arguments, then
11821 // break out so that we will build the appropriate built-in
11822 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011823 ExprResult InputRes =
11824 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11825 Best->Conversions[0], AA_Passing);
11826 if (InputRes.isInvalid())
11827 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011828 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011829 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011830 }
John Wiegley01296292011-04-08 18:41:53 +000011831 }
11832
11833 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011834 // This is an erroneous use of an operator which can be overloaded by
11835 // a non-member function. Check for non-member operators which were
11836 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011837 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011838 // FIXME: Recover by calling the found function.
11839 return ExprError();
11840
John Wiegley01296292011-04-08 18:41:53 +000011841 // No viable function; fall through to handling this as a
11842 // built-in operator, which will produce an error message for us.
11843 break;
11844
11845 case OR_Ambiguous:
11846 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11847 << UnaryOperator::getOpcodeStr(Opc)
11848 << Input->getType()
11849 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011850 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011851 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11852 return ExprError();
11853
11854 case OR_Deleted:
11855 Diag(OpLoc, diag::err_ovl_deleted_oper)
11856 << Best->Function->isDeleted()
11857 << UnaryOperator::getOpcodeStr(Opc)
11858 << getDeletedOrUnavailableSuffix(Best->Function)
11859 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011860 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011861 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011862 return ExprError();
11863 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011864
11865 // Either we found no viable overloaded operator or we matched a
11866 // built-in operator. In either case, fall through to trying to
11867 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011868 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011869}
11870
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011871/// \brief Create a binary operation that may resolve to an overloaded
11872/// operator.
11873///
11874/// \param OpLoc The location of the operator itself (e.g., '+').
11875///
Craig Toppera92ffb02015-12-10 08:51:49 +000011876/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011877///
James Dennett18348b62012-06-22 08:52:37 +000011878/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011879/// considered by overload resolution. The caller needs to build this
11880/// set based on the context using, e.g.,
11881/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11882/// set should not contain any member functions; those will be added
11883/// by CreateOverloadedBinOp().
11884///
11885/// \param LHS Left-hand argument.
11886/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011887ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011888Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011889 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011890 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011891 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011892 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011893 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011894
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011895 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11896 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11897
11898 // If either side is type-dependent, create an appropriate dependent
11899 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011900 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011901 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011902 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011903 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011904 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011905 return new (Context) BinaryOperator(
11906 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11907 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011908
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011909 return new (Context) CompoundAssignOperator(
11910 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11911 Context.DependentTy, Context.DependentTy, OpLoc,
11912 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011913 }
John McCall4c4c1df2010-01-26 03:27:55 +000011914
11915 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011916 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011917 // TODO: provide better source location info in DNLoc component.
11918 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011919 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011920 = UnresolvedLookupExpr::Create(Context, NamingClass,
11921 NestedNameSpecifierLoc(), OpNameInfo,
11922 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011923 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011924 return new (Context)
11925 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11926 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011927 }
11928
John McCall4124c492011-10-17 18:40:02 +000011929 // Always do placeholder-like conversions on the RHS.
11930 if (checkPlaceholderForOverload(*this, Args[1]))
11931 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011932
John McCall526ab472011-10-25 17:37:35 +000011933 // Do placeholder-like conversion on the LHS; note that we should
11934 // not get here with a PseudoObject LHS.
11935 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011936 if (checkPlaceholderForOverload(*this, Args[0]))
11937 return ExprError();
11938
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011939 // If this is the assignment operator, we only perform overload resolution
11940 // if the left-hand side is a class or enumeration type. This is actually
11941 // a hack. The standard requires that we do overload resolution between the
11942 // various built-in candidates, but as DR507 points out, this can lead to
11943 // problems. So we do it this way, which pretty much follows what GCC does.
11944 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011945 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011946 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011947
John McCalle26a8722010-12-04 08:14:53 +000011948 // If this is the .* operator, which is not overloadable, just
11949 // create a built-in binary operator.
11950 if (Opc == BO_PtrMemD)
11951 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11952
Douglas Gregor084d8552009-03-13 23:49:33 +000011953 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011954 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011955
11956 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011957 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011958
11959 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011960 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011961
Richard Smith0daabd72014-09-23 20:31:39 +000011962 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11963 // performed for an assignment operator (nor for operator[] nor operator->,
11964 // which don't get here).
11965 if (Opc != BO_Assign)
11966 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11967 /*ExplicitTemplateArgs*/ nullptr,
11968 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011969
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011970 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011971 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011972
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011973 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11974
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011975 // Perform overload resolution.
11976 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011977 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011978 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011979 // We found a built-in operator or an overloaded operator.
11980 FunctionDecl *FnDecl = Best->Function;
11981
11982 if (FnDecl) {
11983 // We matched an overloaded operator. Build a call to that
11984 // operator.
11985
11986 // Convert the arguments.
11987 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011988 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011989 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011990
Chandler Carruth8e543b32010-12-12 08:17:55 +000011991 ExprResult Arg1 =
11992 PerformCopyInitialization(
11993 InitializedEntity::InitializeParameter(Context,
11994 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011995 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011996 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011997 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011998
John Wiegley01296292011-04-08 18:41:53 +000011999 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012000 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012001 Best->FoundDecl, Method);
12002 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012003 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012004 Args[0] = Arg0.getAs<Expr>();
12005 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012006 } else {
12007 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012008 ExprResult Arg0 = PerformCopyInitialization(
12009 InitializedEntity::InitializeParameter(Context,
12010 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012011 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012012 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012013 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012014
Chandler Carruth8e543b32010-12-12 08:17:55 +000012015 ExprResult Arg1 =
12016 PerformCopyInitialization(
12017 InitializedEntity::InitializeParameter(Context,
12018 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012019 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012020 if (Arg1.isInvalid())
12021 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012022 Args[0] = LHS = Arg0.getAs<Expr>();
12023 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012024 }
12025
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012026 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012027 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012028 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012029 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012030 if (FnExpr.isInvalid())
12031 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012032
Richard Smithc1564702013-11-15 02:58:23 +000012033 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012034 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012035 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12036 ResultTy = ResultTy.getNonLValueExprType(Context);
12037
John McCallb268a282010-08-23 23:25:46 +000012038 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012039 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012040 Args, ResultTy, VK, OpLoc,
12041 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012042
Alp Toker314cc812014-01-25 16:55:45 +000012043 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012044 FnDecl))
12045 return ExprError();
12046
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012047 ArrayRef<const Expr *> ArgsArray(Args, 2);
12048 // Cut off the implicit 'this'.
12049 if (isa<CXXMethodDecl>(FnDecl))
12050 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012051
12052 // Check for a self move.
12053 if (Op == OO_Equal)
12054 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12055
Douglas Gregorb4866e82015-06-19 18:13:19 +000012056 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012057 TheCall->getSourceRange(), VariadicDoesNotApply);
12058
John McCallb268a282010-08-23 23:25:46 +000012059 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012060 } else {
12061 // We matched a built-in operator. Convert the arguments, then
12062 // break out so that we will build the appropriate built-in
12063 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012064 ExprResult ArgsRes0 =
12065 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12066 Best->Conversions[0], AA_Passing);
12067 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012068 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012069 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012070
John Wiegley01296292011-04-08 18:41:53 +000012071 ExprResult ArgsRes1 =
12072 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12073 Best->Conversions[1], AA_Passing);
12074 if (ArgsRes1.isInvalid())
12075 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012076 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012077 break;
12078 }
12079 }
12080
Douglas Gregor66950a32009-09-30 21:46:01 +000012081 case OR_No_Viable_Function: {
12082 // C++ [over.match.oper]p9:
12083 // If the operator is the operator , [...] and there are no
12084 // viable functions, then the operator is assumed to be the
12085 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012086 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012087 break;
12088
Chandler Carruth8e543b32010-12-12 08:17:55 +000012089 // For class as left operand for assignment or compound assigment
12090 // operator do not fall through to handling in built-in, but report that
12091 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012092 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012093 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012094 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012095 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12096 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012097 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012098 if (Args[0]->getType()->isIncompleteType()) {
12099 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12100 << Args[0]->getType()
12101 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12102 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012103 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012104 // This is an erroneous use of an operator which can be overloaded by
12105 // a non-member function. Check for non-member operators which were
12106 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012107 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012108 // FIXME: Recover by calling the found function.
12109 return ExprError();
12110
Douglas Gregor66950a32009-09-30 21:46:01 +000012111 // No viable function; try to create a built-in operation, which will
12112 // produce an error. Then, show the non-viable candidates.
12113 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012114 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012115 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012116 "C++ binary operator overloading is missing candidates!");
12117 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012118 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012119 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012120 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012121 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012122
12123 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012124 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012125 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012126 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012127 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012128 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012129 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012130 return ExprError();
12131
12132 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012133 if (isImplicitlyDeleted(Best->Function)) {
12134 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12135 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012136 << Context.getRecordType(Method->getParent())
12137 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012138
Richard Smithde1a4872012-12-28 12:23:24 +000012139 // The user probably meant to call this special member. Just
12140 // explain why it's deleted.
12141 NoteDeletedFunction(Method);
12142 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012143 } else {
12144 Diag(OpLoc, diag::err_ovl_deleted_oper)
12145 << Best->Function->isDeleted()
12146 << BinaryOperator::getOpcodeStr(Opc)
12147 << getDeletedOrUnavailableSuffix(Best->Function)
12148 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12149 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012150 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012151 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012152 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012153 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012154
Douglas Gregor66950a32009-09-30 21:46:01 +000012155 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012156 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012157}
12158
John McCalldadc5752010-08-24 06:29:42 +000012159ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012160Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12161 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012162 Expr *Base, Expr *Idx) {
12163 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012164 DeclarationName OpName =
12165 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12166
12167 // If either side is type-dependent, create an appropriate dependent
12168 // expression.
12169 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12170
Craig Topperc3ec1492014-05-26 06:22:03 +000012171 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012172 // CHECKME: no 'operator' keyword?
12173 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12174 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012175 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012176 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012177 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012178 /*ADL*/ true, /*Overloaded*/ false,
12179 UnresolvedSetIterator(),
12180 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012181 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012182
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012183 return new (Context)
12184 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12185 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012186 }
12187
John McCall4124c492011-10-17 18:40:02 +000012188 // Handle placeholders on both operands.
12189 if (checkPlaceholderForOverload(*this, Args[0]))
12190 return ExprError();
12191 if (checkPlaceholderForOverload(*this, Args[1]))
12192 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012193
Sebastian Redladba46e2009-10-29 20:17:01 +000012194 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012195 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012196
12197 // Subscript can only be overloaded as a member function.
12198
12199 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012200 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012201
12202 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012203 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012204
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012205 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12206
Sebastian Redladba46e2009-10-29 20:17:01 +000012207 // Perform overload resolution.
12208 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012209 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012210 case OR_Success: {
12211 // We found a built-in operator or an overloaded operator.
12212 FunctionDecl *FnDecl = Best->Function;
12213
12214 if (FnDecl) {
12215 // We matched an overloaded operator. Build a call to that
12216 // operator.
12217
John McCalla0296f72010-03-19 07:35:19 +000012218 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012219
Sebastian Redladba46e2009-10-29 20:17:01 +000012220 // Convert the arguments.
12221 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012222 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012223 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012224 Best->FoundDecl, Method);
12225 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012226 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012227 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012228
Anders Carlssona68e51e2010-01-29 18:37:50 +000012229 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012230 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012231 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012232 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012233 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012234 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012235 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012236 if (InputInit.isInvalid())
12237 return ExprError();
12238
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012239 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012240
Sebastian Redladba46e2009-10-29 20:17:01 +000012241 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012242 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12243 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012244 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012245 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012246 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012247 OpLocInfo.getLoc(),
12248 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012249 if (FnExpr.isInvalid())
12250 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012251
Richard Smithc1564702013-11-15 02:58:23 +000012252 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012253 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012254 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12255 ResultTy = ResultTy.getNonLValueExprType(Context);
12256
John McCallb268a282010-08-23 23:25:46 +000012257 CXXOperatorCallExpr *TheCall =
12258 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012259 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012260 ResultTy, VK, RLoc,
12261 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012262
Alp Toker314cc812014-01-25 16:55:45 +000012263 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012264 return ExprError();
12265
John McCallb268a282010-08-23 23:25:46 +000012266 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012267 } else {
12268 // We matched a built-in operator. Convert the arguments, then
12269 // break out so that we will build the appropriate built-in
12270 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012271 ExprResult ArgsRes0 =
12272 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12273 Best->Conversions[0], AA_Passing);
12274 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012275 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012276 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012277
12278 ExprResult ArgsRes1 =
12279 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12280 Best->Conversions[1], AA_Passing);
12281 if (ArgsRes1.isInvalid())
12282 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012283 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012284
12285 break;
12286 }
12287 }
12288
12289 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012290 if (CandidateSet.empty())
12291 Diag(LLoc, diag::err_ovl_no_oper)
12292 << Args[0]->getType() << /*subscript*/ 0
12293 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12294 else
12295 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12296 << Args[0]->getType()
12297 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012298 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012299 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012300 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012301 }
12302
12303 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012304 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012305 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012306 << Args[0]->getType() << Args[1]->getType()
12307 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012308 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012309 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012310 return ExprError();
12311
12312 case OR_Deleted:
12313 Diag(LLoc, diag::err_ovl_deleted_oper)
12314 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012315 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012316 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012317 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012318 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012319 return ExprError();
12320 }
12321
12322 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012323 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012324}
12325
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012326/// BuildCallToMemberFunction - Build a call to a member
12327/// function. MemExpr is the expression that refers to the member
12328/// function (and includes the object parameter), Args/NumArgs are the
12329/// arguments to the function call (not including the object
12330/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012331/// expression refers to a non-static member function or an overloaded
12332/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012333ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012334Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012335 SourceLocation LParenLoc,
12336 MultiExprArg Args,
12337 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012338 assert(MemExprE->getType() == Context.BoundMemberTy ||
12339 MemExprE->getType() == Context.OverloadTy);
12340
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012341 // Dig out the member expression. This holds both the object
12342 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012343 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012344
John McCall0009fcc2011-04-26 20:42:42 +000012345 // Determine whether this is a call to a pointer-to-member function.
12346 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12347 assert(op->getType() == Context.BoundMemberTy);
12348 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12349
12350 QualType fnType =
12351 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12352
12353 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12354 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012355 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012356
12357 // Check that the object type isn't more qualified than the
12358 // member function we're calling.
12359 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12360
12361 QualType objectType = op->getLHS()->getType();
12362 if (op->getOpcode() == BO_PtrMemI)
12363 objectType = objectType->castAs<PointerType>()->getPointeeType();
12364 Qualifiers objectQuals = objectType.getQualifiers();
12365
12366 Qualifiers difference = objectQuals - funcQuals;
12367 difference.removeObjCGCAttr();
12368 difference.removeAddressSpace();
12369 if (difference) {
12370 std::string qualsString = difference.getAsString();
12371 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12372 << fnType.getUnqualifiedType()
12373 << qualsString
12374 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12375 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012376
John McCall0009fcc2011-04-26 20:42:42 +000012377 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012378 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012379 resultType, valueKind, RParenLoc);
12380
Alp Toker314cc812014-01-25 16:55:45 +000012381 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012382 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012383 return ExprError();
12384
Craig Topperc3ec1492014-05-26 06:22:03 +000012385 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012386 return ExprError();
12387
Richard Trieu9be9c682013-06-22 02:30:38 +000012388 if (CheckOtherCall(call, proto))
12389 return ExprError();
12390
John McCall0009fcc2011-04-26 20:42:42 +000012391 return MaybeBindToTemporary(call);
12392 }
12393
David Majnemerced8bdf2015-02-25 17:36:15 +000012394 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12395 return new (Context)
12396 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12397
John McCall4124c492011-10-17 18:40:02 +000012398 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012399 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012400 return ExprError();
12401
John McCall10eae182009-11-30 22:42:35 +000012402 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012403 CXXMethodDecl *Method = nullptr;
12404 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12405 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012406 if (isa<MemberExpr>(NakedMemExpr)) {
12407 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012408 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012409 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012410 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012411 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012412 } else {
12413 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012414 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012415
John McCall6e9f8f62009-12-03 04:06:58 +000012416 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012417 Expr::Classification ObjectClassification
12418 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12419 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012420
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012421 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012422 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12423 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012424
John McCall2d74de92009-12-01 22:10:20 +000012425 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012426 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012427 if (UnresExpr->hasExplicitTemplateArgs()) {
12428 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12429 TemplateArgs = &TemplateArgsBuffer;
12430 }
12431
John McCall10eae182009-11-30 22:42:35 +000012432 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12433 E = UnresExpr->decls_end(); I != E; ++I) {
12434
John McCall6e9f8f62009-12-03 04:06:58 +000012435 NamedDecl *Func = *I;
12436 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12437 if (isa<UsingShadowDecl>(Func))
12438 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12439
Douglas Gregor02824322011-01-26 19:30:28 +000012440
Francois Pichet64225792011-01-18 05:04:39 +000012441 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012442 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012443 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012444 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012445 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012446 // If explicit template arguments were provided, we can't call a
12447 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012448 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012449 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012450
John McCalla0296f72010-03-19 07:35:19 +000012451 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012452 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012453 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012454 } else {
John McCall10eae182009-11-30 22:42:35 +000012455 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012456 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012457 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012458 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012459 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012460 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012461 }
Mike Stump11289f42009-09-09 15:08:12 +000012462
John McCall10eae182009-11-30 22:42:35 +000012463 DeclarationName DeclName = UnresExpr->getMemberName();
12464
John McCall4124c492011-10-17 18:40:02 +000012465 UnbridgedCasts.restore();
12466
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012467 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012468 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012469 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012470 case OR_Success:
12471 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012472 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012473 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012474 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12475 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012476 // If FoundDecl is different from Method (such as if one is a template
12477 // and the other a specialization), make sure DiagnoseUseOfDecl is
12478 // called on both.
12479 // FIXME: This would be more comprehensively addressed by modifying
12480 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12481 // being used.
12482 if (Method != FoundDecl.getDecl() &&
12483 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12484 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012485 break;
12486
12487 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012488 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012489 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012490 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012491 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012492 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012493 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012494
12495 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012496 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012497 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012498 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012499 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012500 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012501
12502 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012503 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012504 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012505 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012506 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012507 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012508 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012509 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012510 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012511 }
12512
John McCall16df1e52010-03-30 21:47:33 +000012513 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012514
John McCall2d74de92009-12-01 22:10:20 +000012515 // If overload resolution picked a static member, build a
12516 // non-member call based on that function.
12517 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012518 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12519 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012520 }
12521
John McCall10eae182009-11-30 22:42:35 +000012522 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012523 }
12524
Alp Toker314cc812014-01-25 16:55:45 +000012525 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012526 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12527 ResultType = ResultType.getNonLValueExprType(Context);
12528
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012529 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012530 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012531 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012532 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012533
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012534 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012535 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012536 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012537 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012538
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012539 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012540 // We only need to do this if there was actually an overload; otherwise
12541 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012542 if (!Method->isStatic()) {
12543 ExprResult ObjectArg =
12544 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12545 FoundDecl, Method);
12546 if (ObjectArg.isInvalid())
12547 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012548 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012549 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012550
12551 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012552 const FunctionProtoType *Proto =
12553 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012554 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012555 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012556 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012557
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012558 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012559
Richard Smith55ce3522012-06-25 20:30:08 +000012560 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012561 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012562
George Burgess IVaea6ade2015-09-25 17:53:16 +000012563 // In the case the method to call was not selected by the overloading
12564 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012565 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000012566 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000012567 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000012568 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000012569 diag::err_ovl_no_viable_member_function_in_call)
12570 << Method << Method->getSourceRange();
12571 Diag(Method->getLocation(),
12572 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12573 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12574 return ExprError();
12575 }
12576 }
12577
Anders Carlsson47061ee2011-05-06 14:25:31 +000012578 if ((isa<CXXConstructorDecl>(CurContext) ||
12579 isa<CXXDestructorDecl>(CurContext)) &&
12580 TheCall->getMethodDecl()->isPure()) {
12581 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12582
Davide Italianoccb37382015-07-14 23:36:10 +000012583 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12584 MemExpr->performsVirtualDispatch(getLangOpts())) {
12585 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012586 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12587 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12588 << MD->getParent()->getDeclName();
12589
12590 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012591 if (getLangOpts().AppleKext)
12592 Diag(MemExpr->getLocStart(),
12593 diag::note_pure_qualified_call_kext)
12594 << MD->getParent()->getDeclName()
12595 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012596 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012597 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012598
12599 if (CXXDestructorDecl *DD =
12600 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12601 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012602 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012603 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12604 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12605 MemExpr->getMemberLoc());
12606 }
12607
John McCallb268a282010-08-23 23:25:46 +000012608 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012609}
12610
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012611/// BuildCallToObjectOfClassType - Build a call to an object of class
12612/// type (C++ [over.call.object]), which can end up invoking an
12613/// overloaded function call operator (@c operator()) or performing a
12614/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012615ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012616Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012617 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012618 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012619 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012620 if (checkPlaceholderForOverload(*this, Obj))
12621 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012622 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012623
12624 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012625 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012626 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012627
Nico Weberb58e51c2014-11-19 05:21:39 +000012628 assert(Object.get()->getType()->isRecordType() &&
12629 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012630 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012631
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012632 // C++ [over.call.object]p1:
12633 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012634 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012635 // candidate functions includes at least the function call
12636 // operators of T. The function call operators of T are obtained by
12637 // ordinary lookup of the name operator() in the context of
12638 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012639 OverloadCandidateSet CandidateSet(LParenLoc,
12640 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012641 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012642
John Wiegley01296292011-04-08 18:41:53 +000012643 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012644 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012645 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012646
John McCall27b18f82009-11-17 02:14:36 +000012647 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12648 LookupQualifiedName(R, Record->getDecl());
12649 R.suppressDiagnostics();
12650
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012651 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012652 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012653 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012654 Object.get()->Classify(Context),
12655 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012656 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012657 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012658
Douglas Gregorab7897a2008-11-19 22:57:39 +000012659 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012660 // In addition, for each (non-explicit in C++0x) conversion function
12661 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012662 //
12663 // operator conversion-type-id () cv-qualifier;
12664 //
12665 // where cv-qualifier is the same cv-qualification as, or a
12666 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012667 // denotes the type "pointer to function of (P1,...,Pn) returning
12668 // R", or the type "reference to pointer to function of
12669 // (P1,...,Pn) returning R", or the type "reference to function
12670 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012671 // is also considered as a candidate function. Similarly,
12672 // surrogate call functions are added to the set of candidate
12673 // functions for each conversion function declared in an
12674 // accessible base class provided the function is not hidden
12675 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012676 const auto &Conversions =
12677 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12678 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012679 NamedDecl *D = *I;
12680 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12681 if (isa<UsingShadowDecl>(D))
12682 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012683
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012684 // Skip over templated conversion functions; they aren't
12685 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012686 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012687 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012688
John McCall6e9f8f62009-12-03 04:06:58 +000012689 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012690 if (!Conv->isExplicit()) {
12691 // Strip the reference type (if any) and then the pointer type (if
12692 // any) to get down to what might be a function type.
12693 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12694 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12695 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012696
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012697 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12698 {
12699 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012700 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012701 }
12702 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012703 }
Mike Stump11289f42009-09-09 15:08:12 +000012704
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012705 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12706
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012707 // Perform overload resolution.
12708 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012709 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012710 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012711 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012712 // Overload resolution succeeded; we'll build the appropriate call
12713 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012714 break;
12715
12716 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012717 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012718 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012719 << Object.get()->getType() << /*call*/ 1
12720 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012721 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012722 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012723 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012724 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012725 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012726 break;
12727
12728 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012729 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012730 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012731 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012732 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012733 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012734
12735 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012736 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012737 diag::err_ovl_deleted_object_call)
12738 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012739 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012740 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012741 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012742 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012743 break;
Mike Stump11289f42009-09-09 15:08:12 +000012744 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012745
Douglas Gregorb412e172010-07-25 18:17:45 +000012746 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012747 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012748
John McCall4124c492011-10-17 18:40:02 +000012749 UnbridgedCasts.restore();
12750
Craig Topperc3ec1492014-05-26 06:22:03 +000012751 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012752 // Since there is no function declaration, this is one of the
12753 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012754 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012755 = cast<CXXConversionDecl>(
12756 Best->Conversions[0].UserDefined.ConversionFunction);
12757
Craig Topperc3ec1492014-05-26 06:22:03 +000012758 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12759 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012760 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12761 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012762 assert(Conv == Best->FoundDecl.getDecl() &&
12763 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012764 // We selected one of the surrogate functions that converts the
12765 // object parameter to a function pointer. Perform the conversion
12766 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012767
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012768 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012769 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012770 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12771 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012772 if (Call.isInvalid())
12773 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012774 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012775 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12776 CK_UserDefinedConversion, Call.get(),
12777 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012778
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012779 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012780 }
12781
Craig Topperc3ec1492014-05-26 06:22:03 +000012782 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012783
Douglas Gregorab7897a2008-11-19 22:57:39 +000012784 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12785 // that calls this method, using Object for the implicit object
12786 // parameter and passing along the remaining arguments.
12787 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012788
12789 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012790 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012791 return ExprError();
12792
Chandler Carruth8e543b32010-12-12 08:17:55 +000012793 const FunctionProtoType *Proto =
12794 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012795
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012796 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012797
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012798 DeclarationNameInfo OpLocInfo(
12799 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12800 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012801 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012802 HadMultipleCandidates,
12803 OpLocInfo.getLoc(),
12804 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012805 if (NewFn.isInvalid())
12806 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012807
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012808 // Build the full argument list for the method call (the implicit object
12809 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000012810 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012811 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000012812 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012813
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012814 // Once we've built TheCall, all of the expressions are properly
12815 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012816 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012817 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12818 ResultTy = ResultTy.getNonLValueExprType(Context);
12819
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012820 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000012821 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
12822 VK, RParenLoc, false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012823
Alp Toker314cc812014-01-25 16:55:45 +000012824 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012825 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012826
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012827 // We may have default arguments. If so, we need to allocate more
12828 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012829 if (Args.size() < NumParams)
12830 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012831
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012832 bool IsError = false;
12833
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012834 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012835 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012836 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012837 Best->FoundDecl, Method);
12838 if (ObjRes.isInvalid())
12839 IsError = true;
12840 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012841 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012842 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012843
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012844 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012845 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012846 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012847 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012848 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012849
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012850 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012851
John McCalldadc5752010-08-24 06:29:42 +000012852 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012853 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012854 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012855 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012856 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012857
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012858 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012859 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012860 } else {
John McCalldadc5752010-08-24 06:29:42 +000012861 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012862 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12863 if (DefArg.isInvalid()) {
12864 IsError = true;
12865 break;
12866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012867
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012868 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012869 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012870
12871 TheCall->setArg(i + 1, Arg);
12872 }
12873
12874 // If this is a variadic call, handle args passed through "...".
12875 if (Proto->isVariadic()) {
12876 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012877 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012878 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12879 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012880 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012881 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012882 }
12883 }
12884
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012885 if (IsError) return true;
12886
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012887 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012888
Richard Smith55ce3522012-06-25 20:30:08 +000012889 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012890 return true;
12891
John McCalle172be52010-08-24 06:09:16 +000012892 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012893}
12894
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012895/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012896/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012897/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012898ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012899Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12900 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012901 assert(Base->getType()->isRecordType() &&
12902 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012903
John McCall4124c492011-10-17 18:40:02 +000012904 if (checkPlaceholderForOverload(*this, Base))
12905 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012906
John McCallbc077cf2010-02-08 23:07:23 +000012907 SourceLocation Loc = Base->getExprLoc();
12908
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012909 // C++ [over.ref]p1:
12910 //
12911 // [...] An expression x->m is interpreted as (x.operator->())->m
12912 // for a class object x of type T if T::operator->() exists and if
12913 // the operator is selected as the best match function by the
12914 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012915 DeclarationName OpName =
12916 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012917 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012918 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012919
John McCallbc077cf2010-02-08 23:07:23 +000012920 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012921 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012922 return ExprError();
12923
John McCall27b18f82009-11-17 02:14:36 +000012924 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12925 LookupQualifiedName(R, BaseRecord->getDecl());
12926 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012927
12928 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012929 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012930 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012931 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012932 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012933
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012934 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12935
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012936 // Perform overload resolution.
12937 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012938 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012939 case OR_Success:
12940 // Overload resolution succeeded; we'll build the call below.
12941 break;
12942
12943 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012944 if (CandidateSet.empty()) {
12945 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012946 if (NoArrowOperatorFound) {
12947 // Report this specific error to the caller instead of emitting a
12948 // diagnostic, as requested.
12949 *NoArrowOperatorFound = true;
12950 return ExprError();
12951 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012952 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12953 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012954 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012955 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012956 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012957 }
12958 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012959 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012960 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012961 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012962 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012963
12964 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012965 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12966 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012967 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012968 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012969
12970 case OR_Deleted:
12971 Diag(OpLoc, diag::err_ovl_deleted_oper)
12972 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012973 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012974 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012975 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012976 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012977 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012978 }
12979
Craig Topperc3ec1492014-05-26 06:22:03 +000012980 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012981
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012982 // Convert the object parameter.
12983 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012984 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012985 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012986 Best->FoundDecl, Method);
12987 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012988 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012989 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012990
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012991 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012992 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012993 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012994 if (FnExpr.isInvalid())
12995 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012996
Alp Toker314cc812014-01-25 16:55:45 +000012997 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012998 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12999 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000013000 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013001 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000013002 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013003
Alp Toker314cc812014-01-25 16:55:45 +000013004 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013005 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013006
13007 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013008}
13009
Richard Smithbcc22fc2012-03-09 08:00:36 +000013010/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13011/// a literal operator described by the provided lookup results.
13012ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13013 DeclarationNameInfo &SuffixInfo,
13014 ArrayRef<Expr*> Args,
13015 SourceLocation LitEndLoc,
13016 TemplateArgumentListInfo *TemplateArgs) {
13017 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013018
Richard Smith100b24a2014-04-17 01:52:14 +000013019 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13020 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013021 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13022 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013023
Richard Smithbcc22fc2012-03-09 08:00:36 +000013024 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13025
Richard Smithbcc22fc2012-03-09 08:00:36 +000013026 // Perform overload resolution. This will usually be trivial, but might need
13027 // to perform substitutions for a literal operator template.
13028 OverloadCandidateSet::iterator Best;
13029 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13030 case OR_Success:
13031 case OR_Deleted:
13032 break;
13033
13034 case OR_No_Viable_Function:
13035 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13036 << R.getLookupName();
13037 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13038 return ExprError();
13039
13040 case OR_Ambiguous:
13041 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13042 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13043 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013044 }
13045
Richard Smithbcc22fc2012-03-09 08:00:36 +000013046 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013047 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13048 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013049 SuffixInfo.getLoc(),
13050 SuffixInfo.getInfo());
13051 if (Fn.isInvalid())
13052 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013053
13054 // Check the argument types. This should almost always be a no-op, except
13055 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013056 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013057 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013058 ExprResult InputInit = PerformCopyInitialization(
13059 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13060 SourceLocation(), Args[ArgIdx]);
13061 if (InputInit.isInvalid())
13062 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013063 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013064 }
13065
Alp Toker314cc812014-01-25 16:55:45 +000013066 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013067 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13068 ResultTy = ResultTy.getNonLValueExprType(Context);
13069
Richard Smithc67fdd42012-03-07 08:35:16 +000013070 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013071 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013072 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013073 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13074
Alp Toker314cc812014-01-25 16:55:45 +000013075 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013076 return ExprError();
13077
Craig Topperc3ec1492014-05-26 06:22:03 +000013078 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013079 return ExprError();
13080
13081 return MaybeBindToTemporary(UDL);
13082}
13083
Sam Panzer0f384432012-08-21 00:52:01 +000013084/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13085/// given LookupResult is non-empty, it is assumed to describe a member which
13086/// will be invoked. Otherwise, the function will be found via argument
13087/// dependent lookup.
13088/// CallExpr is set to a valid expression and FRS_Success returned on success,
13089/// otherwise CallExpr is set to ExprError() and some non-success value
13090/// is returned.
13091Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013092Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13093 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013094 const DeclarationNameInfo &NameInfo,
13095 LookupResult &MemberLookup,
13096 OverloadCandidateSet *CandidateSet,
13097 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013098 Scope *S = nullptr;
13099
Sam Panzer0f384432012-08-21 00:52:01 +000013100 CandidateSet->clear();
13101 if (!MemberLookup.empty()) {
13102 ExprResult MemberRef =
13103 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13104 /*IsPtr=*/false, CXXScopeSpec(),
13105 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013106 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013107 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013108 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013109 if (MemberRef.isInvalid()) {
13110 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013111 return FRS_DiagnosticIssued;
13112 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013113 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013114 if (CallExpr->isInvalid()) {
13115 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013116 return FRS_DiagnosticIssued;
13117 }
13118 } else {
13119 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013120 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013121 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013122 NestedNameSpecifierLoc(), NameInfo,
13123 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013124 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013125
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013126 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013127 CandidateSet, CallExpr);
13128 if (CandidateSet->empty() || CandidateSetError) {
13129 *CallExpr = ExprError();
13130 return FRS_NoViableFunction;
13131 }
13132 OverloadCandidateSet::iterator Best;
13133 OverloadingResult OverloadResult =
13134 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13135
13136 if (OverloadResult == OR_No_Viable_Function) {
13137 *CallExpr = ExprError();
13138 return FRS_NoViableFunction;
13139 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013140 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013141 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013142 OverloadResult,
13143 /*AllowTypoCorrection=*/false);
13144 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13145 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013146 return FRS_DiagnosticIssued;
13147 }
13148 }
13149 return FRS_Success;
13150}
13151
13152
Douglas Gregorcd695e52008-11-10 20:40:00 +000013153/// FixOverloadedFunctionReference - E is an expression that refers to
13154/// a C++ overloaded function (possibly with some parentheses and
13155/// perhaps a '&' around it). We have resolved the overloaded function
13156/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013157/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013158Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013159 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013160 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013161 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13162 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013163 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013164 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013165
Douglas Gregor51c538b2009-11-20 19:42:02 +000013166 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013167 }
13168
Douglas Gregor51c538b2009-11-20 19:42:02 +000013169 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013170 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13171 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013172 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013173 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013174 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013175 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013176 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013177 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013178
13179 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013180 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013181 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013182 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013183 }
13184
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013185 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13186 if (!GSE->isResultDependent()) {
13187 Expr *SubExpr =
13188 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13189 if (SubExpr == GSE->getResultExpr())
13190 return GSE;
13191
13192 // Replace the resulting type information before rebuilding the generic
13193 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013194 ArrayRef<Expr *> A = GSE->getAssocExprs();
13195 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013196 unsigned ResultIdx = GSE->getResultIndex();
13197 AssocExprs[ResultIdx] = SubExpr;
13198
13199 return new (Context) GenericSelectionExpr(
13200 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13201 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13202 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13203 ResultIdx);
13204 }
13205 // Rather than fall through to the unreachable, return the original generic
13206 // selection expression.
13207 return GSE;
13208 }
13209
Douglas Gregor51c538b2009-11-20 19:42:02 +000013210 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013211 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013212 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013213 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13214 if (Method->isStatic()) {
13215 // Do nothing: static member functions aren't any different
13216 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013217 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013218 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013219 // UnresolvedLookupExpr holding an overloaded member function
13220 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013221 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13222 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013223 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013224 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013225
John McCalld14a8642009-11-21 08:51:07 +000013226 assert(isa<DeclRefExpr>(SubExpr)
13227 && "fixed to something other than a decl ref");
13228 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13229 && "fixed to a member ref with no nested name qualifier");
13230
13231 // We have taken the address of a pointer to member
13232 // function. Perform the computation here so that we get the
13233 // appropriate pointer to member type.
13234 QualType ClassType
13235 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13236 QualType MemPtrType
13237 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013238 // Under the MS ABI, lock down the inheritance model now.
13239 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13240 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013241
John McCall7decc9e2010-11-18 06:31:45 +000013242 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13243 VK_RValue, OK_Ordinary,
13244 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013245 }
13246 }
John McCall16df1e52010-03-30 21:47:33 +000013247 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13248 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013249 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013250 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013251
John McCalle3027922010-08-25 11:45:40 +000013252 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013253 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013254 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013255 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013256 }
John McCalld14a8642009-11-21 08:51:07 +000013257
Richard Smith84a0b6d2016-10-18 23:39:12 +000013258 // C++ [except.spec]p17:
13259 // An exception-specification is considered to be needed when:
13260 // - in an expression the function is the unique lookup result or the
13261 // selected member of a set of overloaded functions
13262 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13263 ResolveExceptionSpec(E->getExprLoc(), FPT);
13264
John McCalld14a8642009-11-21 08:51:07 +000013265 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013266 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013267 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013268 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013269 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13270 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013271 }
13272
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013273 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13274 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013275 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013276 Fn,
John McCall113bee02012-03-10 09:33:50 +000013277 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013278 ULE->getNameLoc(),
13279 Fn->getType(),
13280 VK_LValue,
13281 Found.getDecl(),
13282 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013283 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013284 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13285 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013286 }
13287
John McCall10eae182009-11-30 22:42:35 +000013288 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013289 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013290 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013291 if (MemExpr->hasExplicitTemplateArgs()) {
13292 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13293 TemplateArgs = &TemplateArgsBuffer;
13294 }
John McCall6b51f282009-11-23 01:53:49 +000013295
John McCall2d74de92009-12-01 22:10:20 +000013296 Expr *Base;
13297
John McCall7decc9e2010-11-18 06:31:45 +000013298 // If we're filling in a static method where we used to have an
13299 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013300 if (MemExpr->isImplicitAccess()) {
13301 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013302 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13303 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013304 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013305 Fn,
John McCall113bee02012-03-10 09:33:50 +000013306 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013307 MemExpr->getMemberLoc(),
13308 Fn->getType(),
13309 VK_LValue,
13310 Found.getDecl(),
13311 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013312 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013313 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13314 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013315 } else {
13316 SourceLocation Loc = MemExpr->getMemberLoc();
13317 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013318 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013319 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013320 Base = new (Context) CXXThisExpr(Loc,
13321 MemExpr->getBaseType(),
13322 /*isImplicit=*/true);
13323 }
John McCall2d74de92009-12-01 22:10:20 +000013324 } else
John McCallc3007a22010-10-26 07:05:15 +000013325 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013326
John McCall4adb38c2011-04-27 00:36:17 +000013327 ExprValueKind valueKind;
13328 QualType type;
13329 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13330 valueKind = VK_LValue;
13331 type = Fn->getType();
13332 } else {
13333 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013334 type = Context.BoundMemberTy;
13335 }
13336
13337 MemberExpr *ME = MemberExpr::Create(
13338 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13339 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13340 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13341 OK_Ordinary);
13342 ME->setHadMultipleCandidates(true);
13343 MarkMemberReferenced(ME);
13344 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013346
John McCallc3007a22010-10-26 07:05:15 +000013347 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013348}
13349
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013350ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013351 DeclAccessPair Found,
13352 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013353 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013354}