blob: afdae4ed6d7d357d0e5a4a62590ab01f57209599 [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
George Burgess IV177399e2017-01-09 04:12:14 +000032#include "llvm/ADT/Optional.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000034#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000035#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036#include <algorithm>
David Blaikie8ad22e62014-05-01 23:01:41 +000037#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000038
Richard Smith17c00b42014-11-12 01:24:00 +000039using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000040using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000041
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000042static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
George Burgess IV21081362016-07-24 23:12:40 +000043 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44 return P->hasAttr<PassObjectSizeAttr>();
45 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000046}
47
Nick Lewycky134af912013-02-07 05:08:22 +000048/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000049static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000050CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000052 SourceLocation Loc = SourceLocation(),
53 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000054 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000055 return ExprError();
56 // If FoundDecl is different from Fn (such as if one is a template
57 // and the other a specialization), make sure DiagnoseUseOfDecl is
58 // called on both.
59 // FIXME: This would be more comprehensively addressed by modifying
60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61 // being used.
62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000063 return ExprError();
Richard Smith5f4b3882016-10-19 00:14:23 +000064 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65 S.ResolveExceptionSpec(Loc, FPT);
John McCall113bee02012-03-10 09:33:50 +000066 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000067 VK_LValue, Loc, LocInfo);
68 if (HadMultipleCandidates)
69 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000070
71 S.MarkDeclRefReferenced(DRE);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000072 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000074}
75
John McCall5c32be02010-08-24 20:38:10 +000076static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000078 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000079 bool CStyle,
80 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000081
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000082static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83 QualType &ToType,
84 bool InOverloadResolution,
85 StandardConversionSequence &SCS,
86 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000087static OverloadingResult
88IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89 UserDefinedConversionSequence& User,
90 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000091 bool AllowExplicit,
92 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000093
94
95static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000096CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000097 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareQualificationConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
105static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000106CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000107 const StandardConversionSequence& SCS1,
108 const StandardConversionSequence& SCS2);
109
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000110/// GetConversionRank - Retrieve the implicit conversion rank
111/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000112ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000113 static const ImplicitConversionRank
114 Rank[(int)ICK_Num_Conversion_Kinds] = {
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Exact_Match,
118 ICR_Exact_Match,
119 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000120 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000121 ICR_Promotion,
122 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000123 ICR_Promotion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000131 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000132 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000133 ICR_Conversion,
134 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000135 ICR_Complex_Real_Conversion,
136 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000137 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000138 ICR_Writeback_Conversion,
139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140 // it was omitted by the patch that added
141 // ICK_Zero_Event_Conversion
George Burgess IV2099b542016-09-02 22:59:57 +0000142 ICR_C_Conversion,
143 ICR_C_Conversion_Extension
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000144 };
145 return Rank[(int)Kind];
146}
147
148/// GetImplicitConversionName - Return the name of this kind of
149/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000150static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 "No conversion",
153 "Lvalue-to-rvalue",
154 "Array-to-pointer",
155 "Function-to-pointer",
Richard Smith3c4f8d22016-10-16 17:54:23 +0000156 "Function pointer conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000157 "Qualification",
158 "Integral promotion",
159 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000160 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000161 "Integral conversion",
162 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000163 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000164 "Floating-integral conversion",
165 "Pointer conversion",
166 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000167 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000168 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000169 "Derived-to-base conversion",
170 "Vector conversion",
171 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000172 "Complex-real conversion",
173 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000174 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000175 "Writeback conversion",
176 "OpenCL Zero Event Conversion",
George Burgess IV2099b542016-09-02 22:59:57 +0000177 "C specific type conversion",
178 "Incompatible pointer conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000179 };
180 return Name[Kind];
181}
182
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000183/// StandardConversionSequence - Set the standard conversion
184/// sequence to the identity conversion.
185void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000189 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000190 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000191 ReferenceBinding = false;
192 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000197 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000198 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000199}
200
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000201/// getRank - Retrieve the rank of this standard conversion sequence
202/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203/// implicit conversions.
204ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
212 return Rank;
213}
214
215/// isPointerConversionToBool - Determines whether this conversion is
216/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000217/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000219bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
223 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000224 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000225 (getFromType()->isPointerType() ||
226 getFromType()->isObjCObjectPointerType() ||
227 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000228 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230 return true;
231
232 return false;
233}
234
Douglas Gregor5c407d92008-10-23 00:40:37 +0000235/// isPointerConversionToVoidPointer - Determines whether this
236/// conversion is a conversion of a pointer to a void pointer. This is
237/// used as part of the ranking of standard conversion sequences (C++
238/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000239bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000241isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000242 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000243 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000244
245 // Note that FromType has not necessarily been transformed by the
246 // array-to-pointer implicit conversion, so check for its presence
247 // and redo the conversion to get a pointer.
248 if (First == ICK_Array_To_Pointer)
249 FromType = Context.getArrayDecayedType(FromType);
250
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000253 return ToPtrType->getPointeeType()->isVoidType();
254
255 return false;
256}
257
Richard Smith66e05fe2012-01-18 05:21:49 +0000258/// Skip any implicit casts which could be either part of a narrowing conversion
259/// or after one in an implicit conversion.
260static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262 switch (ICE->getCastKind()) {
263 case CK_NoOp:
264 case CK_IntegralCast:
265 case CK_IntegralToBoolean:
266 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000267 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000268 case CK_FloatingToIntegral:
269 case CK_FloatingToBoolean:
270 case CK_FloatingCast:
271 Converted = ICE->getSubExpr();
272 continue;
273
274 default:
275 return Converted;
276 }
277 }
278
279 return Converted;
280}
281
282/// Check if this standard conversion sequence represents a narrowing
283/// conversion, according to C++11 [dcl.init.list]p7.
284///
285/// \param Ctx The AST context.
286/// \param Converted The result of applying this standard conversion sequence.
287/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
288/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000289/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
290/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000291NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000292StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000294 APValue &ConstantValue,
295 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000296 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000297
298 // C++11 [dcl.init.list]p7:
299 // A narrowing conversion is an implicit conversion ...
300 QualType FromType = getToType(0);
301 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000302
303 // A conversion to an enumeration type is narrowing if the conversion to
304 // the underlying type is narrowing. This only arises for expressions of
305 // the form 'Enum{init}'.
306 if (auto *ET = ToType->getAs<EnumType>())
307 ToType = ET->getDecl()->getIntegerType();
308
Richard Smith66e05fe2012-01-18 05:21:49 +0000309 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000310 // 'bool' is an integral type; dispatch to the right place to handle it.
311 case ICK_Boolean_Conversion:
312 if (FromType->isRealFloatingType())
313 goto FloatingIntegralConversion;
314 if (FromType->isIntegralOrUnscopedEnumerationType())
315 goto IntegralConversion;
316 // Boolean conversions can be from pointers and pointers to members
317 // [conv.bool], and those aren't considered narrowing conversions.
318 return NK_Not_Narrowing;
319
Richard Smith66e05fe2012-01-18 05:21:49 +0000320 // -- from a floating-point type to an integer type, or
321 //
322 // -- from an integer type or unscoped enumeration type to a floating-point
323 // type, except where the source is a constant expression and the actual
324 // value after conversion will fit into the target type and will produce
325 // the original value when converted back to the original type, or
326 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000327 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329 return NK_Type_Narrowing;
330 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331 llvm::APSInt IntConstantValue;
332 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000333
334 // If it's value-dependent, we can't tell whether it's narrowing.
335 if (Initializer->isValueDependent())
336 return NK_Dependent_Narrowing;
337
Richard Smith66e05fe2012-01-18 05:21:49 +0000338 if (Initializer &&
339 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
340 // Convert the integer to the floating type.
341 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
342 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
343 llvm::APFloat::rmNearestTiesToEven);
344 // And back.
345 llvm::APSInt ConvertedValue = IntConstantValue;
346 bool ignored;
347 Result.convertToInteger(ConvertedValue,
348 llvm::APFloat::rmTowardZero, &ignored);
349 // If the resulting value is different, this was a narrowing conversion.
350 if (IntConstantValue != ConvertedValue) {
351 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000352 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000353 return NK_Constant_Narrowing;
354 }
355 } else {
356 // Variables are always narrowings.
357 return NK_Variable_Narrowing;
358 }
359 }
360 return NK_Not_Narrowing;
361
362 // -- from long double to double or float, or from double to float, except
363 // where the source is a constant expression and the actual value after
364 // conversion is within the range of values that can be represented (even
365 // if it cannot be represented exactly), or
366 case ICK_Floating_Conversion:
367 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
368 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
369 // FromType is larger than ToType.
370 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000371
372 // If it's value-dependent, we can't tell whether it's narrowing.
373 if (Initializer->isValueDependent())
374 return NK_Dependent_Narrowing;
375
Richard Smith66e05fe2012-01-18 05:21:49 +0000376 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
377 // Constant!
378 assert(ConstantValue.isFloat());
379 llvm::APFloat FloatVal = ConstantValue.getFloat();
380 // Convert the source value into the target type.
381 bool ignored;
382 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
383 Ctx.getFloatTypeSemantics(ToType),
384 llvm::APFloat::rmNearestTiesToEven, &ignored);
385 // If there was no overflow, the source value is within the range of
386 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000387 if (ConvertStatus & llvm::APFloat::opOverflow) {
388 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000389 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000390 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000391 } else {
392 return NK_Variable_Narrowing;
393 }
394 }
395 return NK_Not_Narrowing;
396
397 // -- from an integer type or unscoped enumeration type to an integer type
398 // that cannot represent all the values of the original type, except where
399 // the source is a constant expression and the actual value after
400 // conversion will fit into the target type and will produce the original
401 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000402 case ICK_Integral_Conversion:
403 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000404 assert(FromType->isIntegralOrUnscopedEnumerationType());
405 assert(ToType->isIntegralOrUnscopedEnumerationType());
406 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
407 const unsigned FromWidth = Ctx.getIntWidth(FromType);
408 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
409 const unsigned ToWidth = Ctx.getIntWidth(ToType);
410
411 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000412 (FromWidth == ToWidth && FromSigned != ToSigned) ||
413 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000414 // Not all values of FromType can be represented in ToType.
415 llvm::APSInt InitializerValue;
416 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith52e624f2016-12-21 21:42:57 +0000417
418 // If it's value-dependent, we can't tell whether it's narrowing.
419 if (Initializer->isValueDependent())
420 return NK_Dependent_Narrowing;
421
Richard Smith25a80d42012-06-13 01:07:41 +0000422 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
423 // Such conversions on variables are always narrowing.
424 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000425 }
426 bool Narrowing = false;
427 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000428 // Negative -> unsigned is narrowing. Otherwise, more bits is never
429 // narrowing.
430 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000431 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000432 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000433 // Add a bit to the InitializerValue so we don't have to worry about
434 // signed vs. unsigned comparisons.
435 InitializerValue = InitializerValue.extend(
436 InitializerValue.getBitWidth() + 1);
437 // Convert the initializer to and from the target width and signed-ness.
438 llvm::APSInt ConvertedValue = InitializerValue;
439 ConvertedValue = ConvertedValue.trunc(ToWidth);
440 ConvertedValue.setIsSigned(ToSigned);
441 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
442 ConvertedValue.setIsSigned(InitializerValue.isSigned());
443 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000444 if (ConvertedValue != InitializerValue)
445 Narrowing = true;
446 }
447 if (Narrowing) {
448 ConstantType = Initializer->getType();
449 ConstantValue = APValue(InitializerValue);
450 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000451 }
452 }
453 return NK_Not_Narrowing;
454 }
455
456 default:
457 // Other kinds of conversions are not narrowings.
458 return NK_Not_Narrowing;
459 }
460}
461
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000462/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000463/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000464LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000465 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466 bool PrintedSomething = false;
467 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000468 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 PrintedSomething = true;
470 }
471
472 if (Second != ICK_Identity) {
473 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000474 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000475 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000476 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000477
478 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000479 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000480 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000481 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000482 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000483 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000484 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000485 PrintedSomething = true;
486 }
487
488 if (Third != ICK_Identity) {
489 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000490 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000492 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493 PrintedSomething = true;
494 }
495
496 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000497 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 }
499}
500
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000501/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000502/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000503void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000504 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000506 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000507 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000508 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000509 if (ConversionFunction)
510 OS << '\'' << *ConversionFunction << '\'';
511 else
512 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000514 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000515 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516 }
517}
518
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000519/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000521void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000522 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000523 if (isStdInitializerListElement())
524 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000525 switch (ConversionKind) {
526 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000527 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000528 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000529 break;
530 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000531 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000532 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533 break;
534 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000535 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000536 break;
John McCall0d1da222010-01-12 00:44:57 +0000537 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000538 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000539 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000540 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000541 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542 break;
543 }
544
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000545 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546}
547
John McCall0d1da222010-01-12 00:44:57 +0000548void AmbiguousConversionSequence::construct() {
549 new (&conversions()) ConversionSet();
550}
551
552void AmbiguousConversionSequence::destruct() {
553 conversions().~ConversionSet();
554}
555
556void
557AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
558 FromTypePtr = O.FromTypePtr;
559 ToTypePtr = O.ToTypePtr;
560 new (&conversions()) ConversionSet(O.conversions());
561}
562
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000563namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000564 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000565 // template argument information.
566 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 TemplateArgument FirstArg;
568 TemplateArgument SecondArg;
569 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000570 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000571 // template parameter and template argument information.
572 struct DFIParamWithArguments : DFIArguments {
573 TemplateParameter Param;
574 };
Richard Smith9b534542015-12-31 02:02:54 +0000575 // Structure used by DeductionFailureInfo to store template argument
576 // information and the index of the problematic call argument.
577 struct DFIDeducedMismatchArgs : DFIArguments {
578 TemplateArgumentList *TemplateArgs;
579 unsigned CallArgIndex;
580 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000581}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000582
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000583/// \brief Convert from Sema's representation of template deduction information
584/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000585DeductionFailureInfo
586clang::MakeDeductionFailureInfo(ASTContext &Context,
587 Sema::TemplateDeductionResult TDK,
588 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000589 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000590 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000591 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000592 switch (TDK) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000593 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000595 case Sema::TDK_TooManyArguments:
596 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000597 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000598 case Sema::TDK_CUDATargetMismatch:
Richard Smith9b534542015-12-31 02:02:54 +0000599 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000603 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000604 Result.Data = Info.Param.getOpaqueValue();
605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Richard Smithc92d2062017-01-05 23:02:44 +0000607 case Sema::TDK_DeducedMismatch:
608 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +0000609 // FIXME: Should allocate from normal heap so that we can free this later.
610 auto *Saved = new (Context) DFIDeducedMismatchArgs;
611 Saved->FirstArg = Info.FirstArg;
612 Saved->SecondArg = Info.SecondArg;
613 Saved->TemplateArgs = Info.take();
614 Saved->CallArgIndex = Info.CallArgIndex;
615 Result.Data = Saved;
616 break;
617 }
618
Richard Smith44ecdbd2013-01-31 05:19:49 +0000619 case Sema::TDK_NonDeducedMismatch: {
620 // FIXME: Should allocate from normal heap so that we can free this later.
621 DFIArguments *Saved = new (Context) DFIArguments;
622 Saved->FirstArg = Info.FirstArg;
623 Saved->SecondArg = Info.SecondArg;
624 Result.Data = Saved;
625 break;
626 }
627
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000629 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000630 // FIXME: Should allocate from normal heap so that we can free this later.
631 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 Saved->Param = Info.Param;
633 Saved->FirstArg = Info.FirstArg;
634 Saved->SecondArg = Info.SecondArg;
635 Result.Data = Saved;
636 break;
637 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000639 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000640 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000641 if (Info.hasSFINAEDiagnostic()) {
642 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
643 SourceLocation(), PartialDiagnostic::NullDiagnostic());
644 Info.takeSFINAEDiagnostic(*Diag);
645 Result.HasDiagnostic = true;
646 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000647 break;
Richard Smith6eedfe72017-01-09 08:01:21 +0000648
649 case Sema::TDK_Success:
650 case Sema::TDK_NonDependentConversionFailure:
651 llvm_unreachable("not a deduction failure");
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000652 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000654 return Result;
655}
John McCall0d1da222010-01-12 00:44:57 +0000656
Larisse Voufo98b20f12013-07-19 23:00:19 +0000657void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000658 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000660 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 case Sema::TDK_InstantiationDepth:
662 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000663 case Sema::TDK_TooManyArguments:
664 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000665 case Sema::TDK_InvalidExplicitArguments:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000666 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000667 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000668 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000670 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000671 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000672 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000673 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000674 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000675 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000676 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000677 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000678
679 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000680 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000681 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000682 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
683 Diag->~PartialDiagnosticAt();
684 HasDiagnostic = false;
685 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000686 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000687
Douglas Gregor461761d2010-05-08 18:20:53 +0000688 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000689 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 break;
691 }
692}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693
Larisse Voufo98b20f12013-07-19 23:00:19 +0000694PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000695 if (HasDiagnostic)
696 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000697 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000698}
699
Larisse Voufo98b20f12013-07-19 23:00:19 +0000700TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000703 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000704 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000707 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000708 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000709 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000710 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000711 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000712 case Sema::TDK_NonDependentConversionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000713 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000714
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000715 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000716 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000718
719 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000720 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000721 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000722
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000723 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000724 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000725 break;
726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000728 return TemplateParameter();
729}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000730
Larisse Voufo98b20f12013-07-19 23:00:19 +0000731TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000733 case Sema::TDK_Success:
734 case Sema::TDK_Invalid:
735 case Sema::TDK_InstantiationDepth:
736 case Sema::TDK_TooManyArguments:
737 case Sema::TDK_TooFewArguments:
738 case Sema::TDK_Incomplete:
739 case Sema::TDK_InvalidExplicitArguments:
740 case Sema::TDK_Inconsistent:
741 case Sema::TDK_Underqualified:
742 case Sema::TDK_NonDeducedMismatch:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000743 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000744 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000745 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000746
Richard Smith9b534542015-12-31 02:02:54 +0000747 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000748 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000749 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
750
Richard Smith44ecdbd2013-01-31 05:19:49 +0000751 case Sema::TDK_SubstitutionFailure:
752 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000753
Richard Smith44ecdbd2013-01-31 05:19:49 +0000754 // Unhandled
755 case Sema::TDK_MiscellaneousDeductionFailure:
756 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000757 }
758
Craig Topperc3ec1492014-05-26 06:22:03 +0000759 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000760}
761
Larisse Voufo98b20f12013-07-19 23:00:19 +0000762const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000763 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000765 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000766 case Sema::TDK_InstantiationDepth:
767 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000768 case Sema::TDK_TooManyArguments:
769 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000770 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000771 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000772 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000773 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000774 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000775
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000776 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000777 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000778 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000779 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000780 case Sema::TDK_NonDeducedMismatch:
781 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000782
Douglas Gregor461761d2010-05-08 18:20:53 +0000783 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000784 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000785 break;
786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000787
Craig Topperc3ec1492014-05-26 06:22:03 +0000788 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000790
Larisse Voufo98b20f12013-07-19 23:00:19 +0000791const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000792 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
793 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000794 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000795 case Sema::TDK_InstantiationDepth:
796 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000797 case Sema::TDK_TooManyArguments:
798 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000799 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000800 case Sema::TDK_SubstitutionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +0000801 case Sema::TDK_CUDATargetMismatch:
Richard Smith6eedfe72017-01-09 08:01:21 +0000802 case Sema::TDK_NonDependentConversionFailure:
Craig Topperc3ec1492014-05-26 06:22:03 +0000803 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000804
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000805 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000806 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000807 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +0000808 case Sema::TDK_DeducedMismatchNested:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000809 case Sema::TDK_NonDeducedMismatch:
810 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000811
Douglas Gregor461761d2010-05-08 18:20:53 +0000812 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000813 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000814 break;
815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816
Craig Topperc3ec1492014-05-26 06:22:03 +0000817 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000818}
819
Richard Smith9b534542015-12-31 02:02:54 +0000820llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
Richard Smithc92d2062017-01-05 23:02:44 +0000821 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
822 case Sema::TDK_DeducedMismatch:
823 case Sema::TDK_DeducedMismatchNested:
Richard Smith9b534542015-12-31 02:02:54 +0000824 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
825
Richard Smithc92d2062017-01-05 23:02:44 +0000826 default:
827 return llvm::None;
828 }
Richard Smith9b534542015-12-31 02:02:54 +0000829}
830
Benjamin Kramer97e59492012-10-09 15:52:25 +0000831void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000832 for (iterator i = begin(), e = end(); i != e; ++i) {
Richard Smith6eedfe72017-01-09 08:01:21 +0000833 for (auto &C : i->Conversions)
834 C.~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000835 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
836 i->DeductionFailure.Destroy();
837 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000838}
839
840void OverloadCandidateSet::clear() {
841 destroyCandidates();
George Burgess IV177399e2017-01-09 04:12:14 +0000842 // DiagnoseIfAttrs are just pointers, so we don't need to destroy them.
843 SlabAllocator.Reset();
844 NumInlineBytesUsed = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000845 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000846 Functions.clear();
847}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000848
George Burgess IV177399e2017-01-09 04:12:14 +0000849DiagnoseIfAttr **
850OverloadCandidateSet::addDiagnoseIfComplaints(ArrayRef<DiagnoseIfAttr *> CA) {
851 auto *DIA = slabAllocate<DiagnoseIfAttr *>(CA.size());
852 std::uninitialized_copy(CA.begin(), CA.end(), DIA);
853 return DIA;
854}
855
John McCall4124c492011-10-17 18:40:02 +0000856namespace {
857 class UnbridgedCastsSet {
858 struct Entry {
859 Expr **Addr;
860 Expr *Saved;
861 };
862 SmallVector<Entry, 2> Entries;
863
864 public:
865 void save(Sema &S, Expr *&E) {
866 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
867 Entry entry = { &E, E };
868 Entries.push_back(entry);
869 E = S.stripARCUnbridgedCast(E);
870 }
871
872 void restore() {
873 for (SmallVectorImpl<Entry>::iterator
874 i = Entries.begin(), e = Entries.end(); i != e; ++i)
875 *i->Addr = i->Saved;
876 }
877 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000878}
John McCall4124c492011-10-17 18:40:02 +0000879
880/// checkPlaceholderForOverload - Do any interesting placeholder-like
881/// preprocessing on the given expression.
882///
883/// \param unbridgedCasts a collection to which to add unbridged casts;
884/// without this, they will be immediately diagnosed as errors
885///
886/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000887static bool
888checkPlaceholderForOverload(Sema &S, Expr *&E,
889 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000890 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
891 // We can't handle overloaded expressions here because overload
892 // resolution might reasonably tweak them.
893 if (placeholder->getKind() == BuiltinType::Overload) return false;
894
895 // If the context potentially accepts unbridged ARC casts, strip
896 // the unbridged cast and add it to the collection for later restoration.
897 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
898 unbridgedCasts) {
899 unbridgedCasts->save(S, E);
900 return false;
901 }
902
903 // Go ahead and check everything else.
904 ExprResult result = S.CheckPlaceholderExpr(E);
905 if (result.isInvalid())
906 return true;
907
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000908 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000909 return false;
910 }
911
912 // Nothing to do.
913 return false;
914}
915
916/// checkArgPlaceholdersForOverload - Check a set of call operands for
917/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000918static bool checkArgPlaceholdersForOverload(Sema &S,
919 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000920 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000921 for (unsigned i = 0, e = Args.size(); i != e; ++i)
922 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000923 return true;
924
925 return false;
926}
927
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000928// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000929// overload of the declarations in Old. This routine returns false if
930// New and Old cannot be overloaded, e.g., if New has the same
931// signature as some function in Old (C++ 1.3.10) or if the Old
932// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000933// it does return false, MatchedDecl will point to the decl that New
934// cannot be overloaded with. This decl may be a UsingShadowDecl on
935// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000936//
937// Example: Given the following input:
938//
939// void f(int, float); // #1
940// void f(int, int); // #2
941// int f(int, int); // #3
942//
943// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000944// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000945//
John McCall3d988d92009-12-02 08:47:38 +0000946// When we process #2, Old contains only the FunctionDecl for #1. By
947// comparing the parameter types, we see that #1 and #2 are overloaded
948// (since they have different signatures), so this routine returns
949// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000950//
John McCall3d988d92009-12-02 08:47:38 +0000951// When we process #3, Old is an overload set containing #1 and #2. We
952// compare the signatures of #3 to #1 (they're overloaded, so we do
953// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
954// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000955// signature), IsOverload returns false and MatchedDecl will be set to
956// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000957//
958// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
959// into a class by a using declaration. The rules for whether to hide
960// shadow declarations ignore some properties which otherwise figure
961// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000962Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000963Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
964 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000965 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000966 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000967 NamedDecl *OldD = *I;
968
969 bool OldIsUsingDecl = false;
970 if (isa<UsingShadowDecl>(OldD)) {
971 OldIsUsingDecl = true;
972
973 // We can always introduce two using declarations into the same
974 // context, even if they have identical signatures.
975 if (NewIsUsingDecl) continue;
976
977 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
978 }
979
Richard Smithf091e122015-09-15 01:28:55 +0000980 // A using-declaration does not conflict with another declaration
981 // if one of them is hidden.
982 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
983 continue;
984
John McCalle9cccd82010-06-16 08:42:20 +0000985 // If either declaration was introduced by a using declaration,
986 // we'll need to use slightly different rules for matching.
987 // Essentially, these rules are the normal rules, except that
988 // function templates hide function templates with different
989 // return types or template parameter lists.
990 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000991 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
992 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000993
Alp Tokera2794f92014-01-22 07:29:52 +0000994 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000995 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
996 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
997 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
998 continue;
999 }
1000
Alp Tokera2794f92014-01-22 07:29:52 +00001001 if (!isa<FunctionTemplateDecl>(OldD) &&
1002 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00001003 continue;
1004
John McCalldaa3d6b2009-12-09 03:35:25 +00001005 Match = *I;
1006 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +00001007 }
Richard Smith151c4562016-12-20 21:35:28 +00001008 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001009 // We can overload with these, which can show up when doing
1010 // redeclaration checks for UsingDecls.
1011 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +00001012 } else if (isa<TagDecl>(OldD)) {
1013 // We can always overload with tags by hiding them.
Richard Smithd8a9e372016-12-18 21:39:37 +00001014 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001015 // Optimistically assume that an unresolved using decl will
1016 // overload; if it doesn't, we'll have to diagnose during
1017 // template instantiation.
Richard Smithd8a9e372016-12-18 21:39:37 +00001018 //
1019 // Exception: if the scope is dependent and this is not a class
1020 // member, the using declaration can only introduce an enumerator.
1021 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1022 Match = *I;
1023 return Ovl_NonFunction;
1024 }
John McCall84d87672009-12-10 09:41:52 +00001025 } else {
John McCall1f82f242009-11-18 22:49:29 +00001026 // (C++ 13p1):
1027 // Only function declarations can be overloaded; object and type
1028 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +00001029 Match = *I;
1030 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +00001031 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001032 }
John McCall1f82f242009-11-18 22:49:29 +00001033
John McCalldaa3d6b2009-12-09 03:35:25 +00001034 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +00001035}
1036
Richard Smithac974a32013-06-30 09:48:50 +00001037bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001038 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001039 // C++ [basic.start.main]p2: This function shall not be overloaded.
1040 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001041 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001042
David Majnemerc729b0b2013-09-16 22:44:20 +00001043 // MSVCRT user defined entry points cannot be overloaded.
1044 if (New->isMSVCRTEntryPoint())
1045 return false;
1046
John McCall1f82f242009-11-18 22:49:29 +00001047 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1048 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1049
1050 // C++ [temp.fct]p2:
1051 // A function template can be overloaded with other function templates
1052 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001053 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001054 return true;
1055
1056 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001057 QualType OldQType = Context.getCanonicalType(Old->getType());
1058 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001059
1060 // Compare the signatures (C++ 1.3.10) of the two functions to
1061 // determine whether they are overloads. If we find any mismatch
1062 // in the signature, they are overloads.
1063
1064 // If either of these functions is a K&R-style function (no
1065 // prototype), then we consider them to have matching signatures.
1066 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1067 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1068 return false;
1069
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001070 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1071 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001072
1073 // The signature of a function includes the types of its
1074 // parameters (C++ 1.3.10), which includes the presence or absence
1075 // of the ellipsis; see C++ DR 357).
1076 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001077 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001078 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001079 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001080 return true;
1081
1082 // C++ [temp.over.link]p4:
1083 // The signature of a function template consists of its function
1084 // signature, its return type and its template parameter list. The names
1085 // of the template parameters are significant only for establishing the
1086 // relationship between the template parameters and the rest of the
1087 // signature.
1088 //
1089 // We check the return type and template parameter lists for function
1090 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001091 //
1092 // However, we don't consider either of these when deciding whether
1093 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001094 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001095 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1096 OldTemplate->getTemplateParameters(),
1097 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001098 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001099 return true;
1100
1101 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001102 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001103 //
1104 // As part of this, also check whether one of the member functions
1105 // is static, in which case they are not overloads (C++
1106 // 13.1p2). While not part of the definition of the signature,
1107 // this check is important to determine whether these functions
1108 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001109 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1110 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001111 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001112 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1113 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001114 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001115 (OldMethod->getRefQualifier() == RQ_None ||
1116 NewMethod->getRefQualifier() == RQ_None)) {
1117 // C++0x [over.load]p2:
1118 // - Member function declarations with the same name and the same
1119 // parameter-type-list as well as member function template
1120 // declarations with the same name, the same parameter-type-list, and
1121 // the same template parameter lists cannot be overloaded if any of
1122 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001123 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001124 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001125 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001126 }
1127 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001129
Richard Smith574f4f62013-01-14 05:37:29 +00001130 // We may not have applied the implicit const for a constexpr member
1131 // function yet (because we haven't yet resolved whether this is a static
1132 // or non-static member function). Add it now, on the assumption that this
1133 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001134 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001135 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001136 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001137 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001138 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001139
1140 // We do not allow overloading based off of '__restrict'.
1141 OldQuals &= ~Qualifiers::Restrict;
1142 NewQuals &= ~Qualifiers::Restrict;
1143 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001144 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001145 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001146
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001147 // Though pass_object_size is placed on parameters and takes an argument, we
1148 // consider it to be a function-level modifier for the sake of function
1149 // identity. Either the function has one or more parameters with
1150 // pass_object_size or it doesn't.
1151 if (functionHasPassObjectSizeParams(New) !=
1152 functionHasPassObjectSizeParams(Old))
1153 return true;
1154
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001155 // enable_if attributes are an order-sensitive part of the signature.
1156 for (specific_attr_iterator<EnableIfAttr>
1157 NewI = New->specific_attr_begin<EnableIfAttr>(),
1158 NewE = New->specific_attr_end<EnableIfAttr>(),
1159 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1160 OldE = Old->specific_attr_end<EnableIfAttr>();
1161 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1162 if (NewI == NewE || OldI == OldE)
1163 return true;
1164 llvm::FoldingSetNodeID NewID, OldID;
1165 NewI->getCond()->Profile(NewID, Context, true);
1166 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001167 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001168 return true;
1169 }
1170
Justin Lebarba122ab2016-03-30 23:30:21 +00001171 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001172 // Don't allow overloading of destructors. (In theory we could, but it
1173 // would be a giant change to clang.)
1174 if (isa<CXXDestructorDecl>(New))
1175 return false;
1176
Artem Belevich94a55e82015-09-22 17:22:59 +00001177 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1178 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001179 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001180 return false;
1181
1182 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1183
Justin Lebar53b000af2016-10-03 16:48:27 +00001184 // Allow overloading of functions with same signature and different CUDA
1185 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001186 return NewTarget != OldTarget;
1187 }
1188
John McCall1f82f242009-11-18 22:49:29 +00001189 // The signatures match; this is not an overload.
1190 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001191}
1192
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001193/// \brief Checks availability of the function depending on the current
1194/// function context. Inside an unavailable function, unavailability is ignored.
1195///
1196/// \returns true if \arg FD is unavailable and current context is inside
1197/// an available function, false otherwise.
1198bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001199 if (!FD->isUnavailable())
1200 return false;
1201
1202 // Walk up the context of the caller.
1203 Decl *C = cast<Decl>(CurContext);
1204 do {
1205 if (C->isUnavailable())
1206 return false;
1207 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1208 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001209}
1210
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001211/// \brief Tries a user-defined conversion from From to ToType.
1212///
1213/// Produces an implicit conversion sequence for when a standard conversion
1214/// is not an option. See TryImplicitConversion for more information.
1215static ImplicitConversionSequence
1216TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1217 bool SuppressUserConversions,
1218 bool AllowExplicit,
1219 bool InOverloadResolution,
1220 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001221 bool AllowObjCWritebackConversion,
1222 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001223 ImplicitConversionSequence ICS;
1224
1225 if (SuppressUserConversions) {
1226 // We're not in the case above, so there is no conversion that
1227 // we can perform.
1228 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1229 return ICS;
1230 }
1231
1232 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001233 OverloadCandidateSet Conversions(From->getExprLoc(),
1234 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001235 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1236 Conversions, AllowExplicit,
1237 AllowObjCConversionOnExplicit)) {
1238 case OR_Success:
1239 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001240 ICS.setUserDefined();
1241 // C++ [over.ics.user]p4:
1242 // A conversion of an expression of class type to the same class
1243 // type is given Exact Match rank, and a conversion of an
1244 // expression of class type to a base class of that type is
1245 // given Conversion rank, in spite of the fact that a copy
1246 // constructor (i.e., a user-defined conversion function) is
1247 // called for those cases.
1248 if (CXXConstructorDecl *Constructor
1249 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1250 QualType FromCanon
1251 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1252 QualType ToCanon
1253 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1254 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001255 (FromCanon == ToCanon ||
1256 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001257 // Turn this into a "standard" conversion sequence, so that it
1258 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001259 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001260 ICS.setStandard();
1261 ICS.Standard.setAsIdentityConversion();
1262 ICS.Standard.setFromType(From->getType());
1263 ICS.Standard.setAllToTypes(ToType);
1264 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001265 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001266 if (ToCanon != FromCanon)
1267 ICS.Standard.Second = ICK_Derived_To_Base;
1268 }
1269 }
Richard Smith48372b62015-01-27 03:30:40 +00001270 break;
1271
1272 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001273 ICS.setAmbiguous();
1274 ICS.Ambiguous.setFromType(From->getType());
1275 ICS.Ambiguous.setToType(ToType);
1276 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1277 Cand != Conversions.end(); ++Cand)
1278 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001279 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001280 break;
Richard Smith48372b62015-01-27 03:30:40 +00001281
1282 // Fall through.
1283 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001284 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001285 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001286 }
1287
1288 return ICS;
1289}
1290
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001291/// TryImplicitConversion - Attempt to perform an implicit conversion
1292/// from the given expression (Expr) to the given type (ToType). This
1293/// function returns an implicit conversion sequence that can be used
1294/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001295///
1296/// void f(float f);
1297/// void g(int i) { f(i); }
1298///
1299/// this routine would produce an implicit conversion sequence to
1300/// describe the initialization of f from i, which will be a standard
1301/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1302/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1303//
1304/// Note that this routine only determines how the conversion can be
1305/// performed; it does not actually perform the conversion. As such,
1306/// it will not produce any diagnostics if no conversion is available,
1307/// but will instead return an implicit conversion sequence of kind
1308/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001309///
1310/// If @p SuppressUserConversions, then user-defined conversions are
1311/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001312/// If @p AllowExplicit, then explicit user-defined conversions are
1313/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001314///
1315/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1316/// writeback conversion, which allows __autoreleasing id* parameters to
1317/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001318static ImplicitConversionSequence
1319TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1320 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001321 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001322 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001323 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001324 bool AllowObjCWritebackConversion,
1325 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001326 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001327 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001328 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001329 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001330 return ICS;
1331 }
1332
David Blaikiebbafb8a2012-03-11 07:00:24 +00001333 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001334 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001335 return ICS;
1336 }
1337
Douglas Gregor836a7e82010-08-11 02:15:33 +00001338 // C++ [over.ics.user]p4:
1339 // A conversion of an expression of class type to the same class
1340 // type is given Exact Match rank, and a conversion of an
1341 // expression of class type to a base class of that type is
1342 // given Conversion rank, in spite of the fact that a copy/move
1343 // constructor (i.e., a user-defined conversion function) is
1344 // called for those cases.
1345 QualType FromType = From->getType();
1346 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001347 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001348 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001349 ICS.setStandard();
1350 ICS.Standard.setAsIdentityConversion();
1351 ICS.Standard.setFromType(FromType);
1352 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001353
Douglas Gregor5ab11652010-04-17 22:01:05 +00001354 // We don't actually check at this point whether there is a valid
1355 // copy/move constructor, since overloading just assumes that it
1356 // exists. When we actually perform initialization, we'll find the
1357 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001358 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359
Douglas Gregor5ab11652010-04-17 22:01:05 +00001360 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001361 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001362 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363
Douglas Gregor836a7e82010-08-11 02:15:33 +00001364 return ICS;
1365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001366
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001367 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1368 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001369 AllowObjCWritebackConversion,
1370 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001371}
1372
John McCall31168b02011-06-15 23:02:42 +00001373ImplicitConversionSequence
1374Sema::TryImplicitConversion(Expr *From, QualType ToType,
1375 bool SuppressUserConversions,
1376 bool AllowExplicit,
1377 bool InOverloadResolution,
1378 bool CStyle,
1379 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001380 return ::TryImplicitConversion(*this, From, ToType,
1381 SuppressUserConversions, AllowExplicit,
1382 InOverloadResolution, CStyle,
1383 AllowObjCWritebackConversion,
1384 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001385}
1386
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001387/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001388/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001389/// converted expression. Flavor is the kind of conversion we're
1390/// performing, used in the error message. If @p AllowExplicit,
1391/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001392ExprResult
1393Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001394 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001395 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001396 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001397}
1398
John Wiegley01296292011-04-08 18:41:53 +00001399ExprResult
1400Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001401 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001402 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001403 if (checkPlaceholderForOverload(*this, From))
1404 return ExprError();
1405
John McCall31168b02011-06-15 23:02:42 +00001406 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1407 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001408 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001409 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001410 if (getLangOpts().ObjC1)
1411 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1412 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001413 ICS = ::TryImplicitConversion(*this, From, ToType,
1414 /*SuppressUserConversions=*/false,
1415 AllowExplicit,
1416 /*InOverloadResolution=*/false,
1417 /*CStyle=*/false,
1418 AllowObjCWritebackConversion,
1419 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001420 return PerformImplicitConversion(From, ToType, ICS, Action);
1421}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422
1423/// \brief Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001424/// conversion that strips "noexcept" or "noreturn" off the nested function
1425/// type.
1426bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001427 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001428 if (Context.hasSameUnqualifiedType(FromType, ToType))
1429 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001430
John McCall991eb4b2010-12-21 00:44:39 +00001431 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001432 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001433 // where F adds one of the following at most once:
1434 // - a pointer
1435 // - a member pointer
1436 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001437 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001438 CanQualType CanTo = Context.getCanonicalType(ToType);
1439 CanQualType CanFrom = Context.getCanonicalType(FromType);
1440 Type::TypeClass TyClass = CanTo->getTypeClass();
1441 if (TyClass != CanFrom->getTypeClass()) return false;
1442 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1443 if (TyClass == Type::Pointer) {
1444 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1445 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1446 } else if (TyClass == Type::BlockPointer) {
1447 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1448 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1449 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001450 auto ToMPT = CanTo.getAs<MemberPointerType>();
1451 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1452 // A function pointer conversion cannot change the class of the function.
1453 if (ToMPT->getClass() != FromMPT->getClass())
1454 return false;
1455 CanTo = ToMPT->getPointeeType();
1456 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001457 } else {
1458 return false;
1459 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001460
John McCall991eb4b2010-12-21 00:44:39 +00001461 TyClass = CanTo->getTypeClass();
1462 if (TyClass != CanFrom->getTypeClass()) return false;
1463 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1464 return false;
1465 }
1466
Richard Smith3c4f8d22016-10-16 17:54:23 +00001467 const auto *FromFn = cast<FunctionType>(CanFrom);
1468 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001469
Richard Smith6f427402016-10-20 00:01:36 +00001470 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001471 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1472
1473 bool Changed = false;
1474
1475 // Drop 'noreturn' if not present in target type.
1476 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1477 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1478 Changed = true;
1479 }
1480
1481 // Drop 'noexcept' if not present in target type.
1482 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001483 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001484 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1485 FromFn = cast<FunctionType>(
1486 Context.getFunctionType(FromFPT->getReturnType(),
1487 FromFPT->getParamTypes(),
1488 FromFPT->getExtProtoInfo().withExceptionSpec(
1489 FunctionProtoType::ExceptionSpecInfo()))
1490 .getTypePtr());
1491 Changed = true;
1492 }
1493 }
1494
1495 if (!Changed)
1496 return false;
1497
John McCall991eb4b2010-12-21 00:44:39 +00001498 assert(QualType(FromFn, 0).isCanonical());
1499 if (QualType(FromFn, 0) != CanTo) return false;
1500
1501 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001502 return true;
1503}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001504
Douglas Gregor46188682010-05-18 22:42:18 +00001505/// \brief Determine whether the conversion from FromType to ToType is a valid
1506/// vector conversion.
1507///
1508/// \param ICK Will be set to the vector conversion kind, if this is a vector
1509/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001510static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001511 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001512 // We need at least one of these types to be a vector type to have a vector
1513 // conversion.
1514 if (!ToType->isVectorType() && !FromType->isVectorType())
1515 return false;
1516
1517 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001518 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001519 return false;
1520
1521 // There are no conversions between extended vector types, only identity.
1522 if (ToType->isExtVectorType()) {
1523 // There are no conversions between extended vector types other than the
1524 // identity conversion.
1525 if (FromType->isExtVectorType())
1526 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001527
Douglas Gregor46188682010-05-18 22:42:18 +00001528 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001529 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001530 ICK = ICK_Vector_Splat;
1531 return true;
1532 }
1533 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001534
1535 // We can perform the conversion between vector types in the following cases:
1536 // 1)vector types are equivalent AltiVec and GCC vector types
1537 // 2)lax vector conversions are permitted and the vector types are of the
1538 // same size
1539 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001540 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1541 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001542 ICK = ICK_Vector_Conversion;
1543 return true;
1544 }
Douglas Gregor46188682010-05-18 22:42:18 +00001545 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001546
Douglas Gregor46188682010-05-18 22:42:18 +00001547 return false;
1548}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001549
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001550static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1551 bool InOverloadResolution,
1552 StandardConversionSequence &SCS,
1553 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001554
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001555/// IsStandardConversion - Determines whether there is a standard
1556/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1557/// expression From to the type ToType. Standard conversion sequences
1558/// only consider non-class types; for conversions that involve class
1559/// types, use TryImplicitConversion. If a conversion exists, SCS will
1560/// contain the standard conversion sequence required to perform this
1561/// conversion and this routine will return true. Otherwise, this
1562/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001563static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1564 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001565 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001566 bool CStyle,
1567 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001568 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001569
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001570 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001571 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001572 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001573 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001574 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001575
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001576 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001577 // abort early. When overloading in C, however, we do permit them.
1578 if (S.getLangOpts().CPlusPlus &&
1579 (FromType->isRecordType() || ToType->isRecordType()))
1580 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001581
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001582 // The first conversion can be an lvalue-to-rvalue conversion,
1583 // array-to-pointer conversion, or function-to-pointer conversion
1584 // (C++ 4p1).
1585
John McCall5c32be02010-08-24 20:38:10 +00001586 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001587 DeclAccessPair AccessPair;
1588 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001589 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001590 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001591 // We were able to resolve the address of the overloaded function,
1592 // so we can convert to the type of that function.
1593 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001594 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001595
1596 // we can sometimes resolve &foo<int> regardless of ToType, so check
1597 // if the type matches (identity) or we are converting to bool
1598 if (!S.Context.hasSameUnqualifiedType(
1599 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1600 QualType resultTy;
1601 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001602 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001603 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1604 // otherwise, only a boolean conversion is standard
1605 if (!ToType->isBooleanType())
1606 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001608
Chandler Carruthffce2452011-03-29 08:08:18 +00001609 // Check if the "from" expression is taking the address of an overloaded
1610 // function and recompute the FromType accordingly. Take advantage of the
1611 // fact that non-static member functions *must* have such an address-of
1612 // expression.
1613 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1614 if (Method && !Method->isStatic()) {
1615 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1616 "Non-unary operator on non-static member address");
1617 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1618 == UO_AddrOf &&
1619 "Non-address-of operator on non-static member address");
1620 const Type *ClassType
1621 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1622 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001623 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1624 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1625 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001626 "Non-address-of operator for overloaded function expression");
1627 FromType = S.Context.getPointerType(FromType);
1628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001629
Douglas Gregor980fb162010-04-29 18:24:40 +00001630 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001631 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1632 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001633 assert(S.Context.hasSameType(
1634 FromType,
1635 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001636 } else {
1637 return false;
1638 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001639 }
John McCall154a2fd2011-08-30 00:57:29 +00001640 // Lvalue-to-rvalue conversion (C++11 4.1):
1641 // A glvalue (3.10) of a non-function, non-array type T can
1642 // be converted to a prvalue.
1643 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001644 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001645 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001646 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001647 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001648
Douglas Gregorc79862f2012-04-12 17:51:55 +00001649 // C11 6.3.2.1p2:
1650 // ... if the lvalue has atomic type, the value has the non-atomic version
1651 // of the type of the lvalue ...
1652 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1653 FromType = Atomic->getValueType();
1654
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001655 // If T is a non-class type, the type of the rvalue is the
1656 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001657 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1658 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001659 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001660 } else if (FromType->isArrayType()) {
1661 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001662 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663
1664 // An lvalue or rvalue of type "array of N T" or "array of unknown
1665 // bound of T" can be converted to an rvalue of type "pointer to
1666 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001667 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001668
John McCall5c32be02010-08-24 20:38:10 +00001669 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001670 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001671 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001672
1673 // For the purpose of ranking in overload resolution
1674 // (13.3.3.1.1), this conversion is considered an
1675 // array-to-pointer conversion followed by a qualification
1676 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001677 SCS.Second = ICK_Identity;
1678 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001679 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001680 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001681 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001682 }
John McCall086a4642010-11-24 05:12:34 +00001683 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001684 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001685 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001686
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001687 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1688 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1689 if (!S.checkAddressOfFunctionIsAvailable(FD))
1690 return false;
1691
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001692 // An lvalue of function type T can be converted to an rvalue of
1693 // type "pointer to T." The result is a pointer to the
1694 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001695 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001696 } else {
1697 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001698 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001699 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001700 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001701
1702 // The second conversion can be an integral promotion, floating
1703 // point promotion, integral conversion, floating point conversion,
1704 // floating-integral conversion, pointer conversion,
1705 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001706 // For overloading in C, this can also be a "compatible-type"
1707 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001708 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001709 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001710 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001711 // The unqualified versions of the types are the same: there's no
1712 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001713 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001714 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001715 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001716 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001717 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001718 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001719 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001720 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001721 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001722 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001723 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001724 SCS.Second = ICK_Complex_Promotion;
1725 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001726 } else if (ToType->isBooleanType() &&
1727 (FromType->isArithmeticType() ||
1728 FromType->isAnyPointerType() ||
1729 FromType->isBlockPointerType() ||
1730 FromType->isMemberPointerType() ||
1731 FromType->isNullPtrType())) {
1732 // Boolean conversions (C++ 4.12).
1733 SCS.Second = ICK_Boolean_Conversion;
1734 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001735 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001736 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001737 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001738 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001739 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001740 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001741 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001742 SCS.Second = ICK_Complex_Conversion;
1743 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001744 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1745 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001746 // Complex-real conversions (C99 6.3.1.7)
1747 SCS.Second = ICK_Complex_Real;
1748 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001749 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001750 // FIXME: disable conversions between long double and __float128 if
1751 // their representation is different until there is back end support
1752 // We of course allow this conversion if long double is really double.
1753 if (&S.Context.getFloatTypeSemantics(FromType) !=
1754 &S.Context.getFloatTypeSemantics(ToType)) {
1755 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1756 ToType == S.Context.LongDoubleTy) ||
1757 (FromType == S.Context.LongDoubleTy &&
1758 ToType == S.Context.Float128Ty));
1759 if (Float128AndLongDouble &&
1760 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001761 &llvm::APFloat::IEEEdouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001762 return false;
1763 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001764 // Floating point conversions (C++ 4.8).
1765 SCS.Second = ICK_Floating_Conversion;
1766 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001767 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001768 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001769 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001770 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001771 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001772 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001773 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001774 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001775 SCS.Second = ICK_Block_Pointer_Conversion;
1776 } else if (AllowObjCWritebackConversion &&
1777 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1778 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001779 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1780 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001781 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001782 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001783 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001784 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001785 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001786 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001787 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001788 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001789 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001790 SCS.Second = SecondICK;
1791 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001792 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001793 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001794 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001795 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001796 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001797 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1798 InOverloadResolution,
1799 SCS, CStyle)) {
1800 SCS.Second = ICK_TransparentUnionConversion;
1801 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001802 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1803 CStyle)) {
1804 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001805 // appropriately.
1806 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001807 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001808 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001809 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001810 SCS.Second = ICK_Zero_Event_Conversion;
1811 FromType = ToType;
Egor Churaev89831422016-12-23 14:55:49 +00001812 } else if (ToType->isQueueT() &&
1813 From->isIntegerConstantExpr(S.getASTContext()) &&
1814 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1815 SCS.Second = ICK_Zero_Queue_Conversion;
1816 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001817 } else {
1818 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001819 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001820 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001821 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001822
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001823 // The third conversion can be a function pointer conversion or a
1824 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001825 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001826 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1827 // Function pointer conversions (removing 'noexcept') including removal of
1828 // 'noreturn' (Clang extension).
1829 SCS.Third = ICK_Function_Conversion;
1830 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1831 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001832 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001833 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001834 FromType = ToType;
1835 } else {
1836 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001837 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001838 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001839
1840 // C++ [over.best.ics]p6:
1841 // [...] Any difference in top-level cv-qualification is
1842 // subsumed by the initialization itself and does not constitute
1843 // a conversion. [...]
1844 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1845 QualType CanonTo = S.Context.getCanonicalType(ToType);
1846 if (CanonFrom.getLocalUnqualifiedType()
1847 == CanonTo.getLocalUnqualifiedType() &&
1848 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1849 FromType = ToType;
1850 CanonFrom = CanonTo;
1851 }
1852
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001853 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001854
George Burgess IV45461812015-10-11 20:13:20 +00001855 if (CanonFrom == CanonTo)
1856 return true;
1857
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001858 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001859 // this is a bad conversion sequence, unless we're resolving an overload in C.
1860 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001861 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001862
George Burgess IV45461812015-10-11 20:13:20 +00001863 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001864 Sema::AssignConvertType Conv =
1865 S.CheckSingleAssignmentConstraints(ToType, ER,
1866 /*Diagnose=*/false,
1867 /*DiagnoseCFAudited=*/false,
1868 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001869 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001870 switch (Conv) {
1871 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001872 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001873 break;
1874 // For our purposes, discarding qualifiers is just as bad as using an
1875 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1876 // qualifiers, as well.
1877 case Sema::CompatiblePointerDiscardsQualifiers:
1878 case Sema::IncompatiblePointer:
1879 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001880 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001881 break;
1882 default:
George Burgess IV45461812015-10-11 20:13:20 +00001883 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001884 }
George Burgess IV45461812015-10-11 20:13:20 +00001885
George Burgess IV6098fd12016-09-03 00:28:25 +00001886 // First can only be an lvalue conversion, so we pretend that this was the
1887 // second conversion. First should already be valid from earlier in the
1888 // function.
1889 SCS.Second = SecondConv;
1890 SCS.setToType(1, ToType);
1891
1892 // Third is Identity, because Second should rank us worse than any other
1893 // conversion. This could also be ICK_Qualification, but it's simpler to just
1894 // lump everything in with the second conversion, and we don't gain anything
1895 // from making this ICK_Qualification.
1896 SCS.Third = ICK_Identity;
1897 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001898 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001899}
George Burgess IV2099b542016-09-02 22:59:57 +00001900
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001901static bool
1902IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1903 QualType &ToType,
1904 bool InOverloadResolution,
1905 StandardConversionSequence &SCS,
1906 bool CStyle) {
1907
1908 const RecordType *UT = ToType->getAsUnionType();
1909 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1910 return false;
1911 // The field to initialize within the transparent union.
1912 RecordDecl *UD = UT->getDecl();
1913 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001914 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001915 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1916 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001917 ToType = it->getType();
1918 return true;
1919 }
1920 }
1921 return false;
1922}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001923
1924/// IsIntegralPromotion - Determines whether the conversion from the
1925/// expression From (whose potentially-adjusted type is FromType) to
1926/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1927/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001928bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001929 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001930 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001931 if (!To) {
1932 return false;
1933 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001934
1935 // An rvalue of type char, signed char, unsigned char, short int, or
1936 // unsigned short int can be converted to an rvalue of type int if
1937 // int can represent all the values of the source type; otherwise,
1938 // the source rvalue can be converted to an rvalue of type unsigned
1939 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001940 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1941 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001942 if (// We can promote any signed, promotable integer type to an int
1943 (FromType->isSignedIntegerType() ||
1944 // We can promote any unsigned integer type whose size is
1945 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001946 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001947 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001948 }
1949
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001950 return To->getKind() == BuiltinType::UInt;
1951 }
1952
Richard Smithb9c5a602012-09-13 21:18:54 +00001953 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954 // A prvalue of an unscoped enumeration type whose underlying type is not
1955 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1956 // following types that can represent all the values of the enumeration
1957 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1958 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001959 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001960 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001961 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001962 // with lowest integer conversion rank (4.13) greater than the rank of long
1963 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001964 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001965 // C++11 [conv.prom]p4:
1966 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1967 // can be converted to a prvalue of its underlying type. Moreover, if
1968 // integral promotion can be applied to its underlying type, a prvalue of an
1969 // unscoped enumeration type whose underlying type is fixed can also be
1970 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001971 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1972 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1973 // provided for a scoped enumeration.
1974 if (FromEnumType->getDecl()->isScoped())
1975 return false;
1976
Richard Smithb9c5a602012-09-13 21:18:54 +00001977 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001978 // even if that's not the promoted type. Note that the check for promoting
1979 // the underlying type is based on the type alone, and does not consider
1980 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001981 if (FromEnumType->getDecl()->isFixed()) {
1982 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1983 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001984 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001985 }
1986
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001987 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001988 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001989 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001990 return Context.hasSameUnqualifiedType(
1991 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001992 }
John McCall56774992009-12-09 09:09:27 +00001993
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001994 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001995 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1996 // to an rvalue a prvalue of the first of the following types that can
1997 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001998 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001999 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002000 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002001 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002002 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00002004 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002005 // Determine whether the type we're converting from is signed or
2006 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00002007 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002008 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002009
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002010 // The types we'll try to promote to, in the appropriate
2011 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00002012 QualType PromoteTypes[6] = {
2013 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00002014 Context.LongTy, Context.UnsignedLongTy ,
2015 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002016 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002017 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002018 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2019 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002020 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002021 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2022 // We found the type that we can promote to. If this is the
2023 // type we wanted, we have a promotion. Otherwise, no
2024 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002025 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002026 }
2027 }
2028 }
2029
2030 // An rvalue for an integral bit-field (9.6) can be converted to an
2031 // rvalue of type int if int can represent all the values of the
2032 // bit-field; otherwise, it can be converted to unsigned int if
2033 // unsigned int can represent all the values of the bit-field. If
2034 // the bit-field is larger yet, no integral promotion applies to
2035 // it. If the bit-field has an enumerated type, it is treated as any
2036 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002037 // FIXME: We should delay checking of bit-fields until we actually perform the
2038 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00002039 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002040 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002041 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002042 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002043 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002044 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002045 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002046
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002047 // Are we promoting to an int from a bitfield that fits in an int?
2048 if (BitWidth < ToSize ||
2049 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2050 return To->getKind() == BuiltinType::Int;
2051 }
Mike Stump11289f42009-09-09 15:08:12 +00002052
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002053 // Are we promoting to an unsigned int from an unsigned bitfield
2054 // that fits into an unsigned int?
2055 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2056 return To->getKind() == BuiltinType::UInt;
2057 }
Mike Stump11289f42009-09-09 15:08:12 +00002058
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002059 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002060 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002061 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002062 }
Mike Stump11289f42009-09-09 15:08:12 +00002063
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002064 // An rvalue of type bool can be converted to an rvalue of type int,
2065 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002066 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002067 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002068 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002069
2070 return false;
2071}
2072
2073/// IsFloatingPointPromotion - Determines whether the conversion from
2074/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2075/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002076bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002077 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2078 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002079 /// An rvalue of type float can be converted to an rvalue of type
2080 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002081 if (FromBuiltin->getKind() == BuiltinType::Float &&
2082 ToBuiltin->getKind() == BuiltinType::Double)
2083 return true;
2084
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002085 // C99 6.3.1.5p1:
2086 // When a float is promoted to double or long double, or a
2087 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002088 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002089 (FromBuiltin->getKind() == BuiltinType::Float ||
2090 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002091 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2092 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002093 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002094
2095 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002096 if (!getLangOpts().NativeHalfType &&
2097 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002098 ToBuiltin->getKind() == BuiltinType::Float)
2099 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002100 }
2101
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002102 return false;
2103}
2104
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002105/// \brief Determine if a conversion is a complex promotion.
2106///
2107/// A complex promotion is defined as a complex -> complex conversion
2108/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002109/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002110bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002111 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002112 if (!FromComplex)
2113 return false;
2114
John McCall9dd450b2009-09-21 23:43:11 +00002115 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002116 if (!ToComplex)
2117 return false;
2118
2119 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002120 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002121 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002122 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002123}
2124
Douglas Gregor237f96c2008-11-26 23:31:11 +00002125/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2126/// the pointer type FromPtr to a pointer to type ToPointee, with the
2127/// same type qualifiers as FromPtr has on its pointee type. ToType,
2128/// if non-empty, will be a pointer to ToType that may or may not have
2129/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002130///
Mike Stump11289f42009-09-09 15:08:12 +00002131static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002132BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002133 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002134 ASTContext &Context,
2135 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002136 assert((FromPtr->getTypeClass() == Type::Pointer ||
2137 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2138 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002139
John McCall31168b02011-06-15 23:02:42 +00002140 /// Conversions to 'id' subsume cv-qualifier conversions.
2141 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002142 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002143
2144 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002145 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002146 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002147 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002148
John McCall31168b02011-06-15 23:02:42 +00002149 if (StripObjCLifetime)
2150 Quals.removeObjCLifetime();
2151
Mike Stump11289f42009-09-09 15:08:12 +00002152 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002153 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002154 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002155 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002156 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002157
2158 // Build a pointer to ToPointee. It has the right qualifiers
2159 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002160 if (isa<ObjCObjectPointerType>(ToType))
2161 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002162 return Context.getPointerType(ToPointee);
2163 }
2164
2165 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002166 QualType QualifiedCanonToPointee
2167 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002168
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002169 if (isa<ObjCObjectPointerType>(ToType))
2170 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2171 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002172}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002173
Mike Stump11289f42009-09-09 15:08:12 +00002174static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002175 bool InOverloadResolution,
2176 ASTContext &Context) {
2177 // Handle value-dependent integral null pointer constants correctly.
2178 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2179 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002180 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002181 return !InOverloadResolution;
2182
Douglas Gregor56751b52009-09-25 04:25:58 +00002183 return Expr->isNullPointerConstant(Context,
2184 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2185 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002186}
Mike Stump11289f42009-09-09 15:08:12 +00002187
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002188/// IsPointerConversion - Determines whether the conversion of the
2189/// expression From, which has the (possibly adjusted) type FromType,
2190/// can be converted to the type ToType via a pointer conversion (C++
2191/// 4.10). If so, returns true and places the converted type (that
2192/// might differ from ToType in its cv-qualifiers at some level) into
2193/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002194///
Douglas Gregora29dc052008-11-27 01:19:21 +00002195/// This routine also supports conversions to and from block pointers
2196/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2197/// pointers to interfaces. FIXME: Once we've determined the
2198/// appropriate overloading rules for Objective-C, we may want to
2199/// split the Objective-C checks into a different routine; however,
2200/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002201/// conversions, so for now they live here. IncompatibleObjC will be
2202/// set if the conversion is an allowed Objective-C conversion that
2203/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002204bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002205 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002206 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002207 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002208 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002209 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2210 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002211 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002212
Mike Stump11289f42009-09-09 15:08:12 +00002213 // Conversion from a null pointer constant to any Objective-C pointer type.
2214 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002215 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002216 ConvertedType = ToType;
2217 return true;
2218 }
2219
Douglas Gregor231d1c62008-11-27 00:15:41 +00002220 // Blocks: Block pointers can be converted to void*.
2221 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002222 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002223 ConvertedType = ToType;
2224 return true;
2225 }
2226 // Blocks: A null pointer constant can be converted to a block
2227 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002228 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002229 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002230 ConvertedType = ToType;
2231 return true;
2232 }
2233
Sebastian Redl576fd422009-05-10 18:38:11 +00002234 // If the left-hand-side is nullptr_t, the right side can be a null
2235 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002236 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002237 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002238 ConvertedType = ToType;
2239 return true;
2240 }
2241
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002242 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002243 if (!ToTypePtr)
2244 return false;
2245
2246 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002247 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002248 ConvertedType = ToType;
2249 return true;
2250 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002251
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002252 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002253 // , including objective-c pointers.
2254 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002255 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002256 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002257 ConvertedType = BuildSimilarlyQualifiedPointerType(
2258 FromType->getAs<ObjCObjectPointerType>(),
2259 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002260 ToType, Context);
2261 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002262 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002263 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002264 if (!FromTypePtr)
2265 return false;
2266
2267 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002268
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002269 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002270 // pointer conversion, so don't do all of the work below.
2271 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2272 return false;
2273
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002274 // An rvalue of type "pointer to cv T," where T is an object type,
2275 // can be converted to an rvalue of type "pointer to cv void" (C++
2276 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002277 if (FromPointeeType->isIncompleteOrObjectType() &&
2278 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002279 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002280 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002281 ToType, Context,
2282 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002283 return true;
2284 }
2285
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002286 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002287 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002288 ToPointeeType->isVoidType()) {
2289 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2290 ToPointeeType,
2291 ToType, Context);
2292 return true;
2293 }
2294
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002295 // When we're overloading in C, we allow a special kind of pointer
2296 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002297 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002298 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002299 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002300 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002301 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002302 return true;
2303 }
2304
Douglas Gregor5c407d92008-10-23 00:40:37 +00002305 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002306 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002307 // An rvalue of type "pointer to cv D," where D is a class type,
2308 // can be converted to an rvalue of type "pointer to cv B," where
2309 // B is a base class (clause 10) of D. If B is an inaccessible
2310 // (clause 11) or ambiguous (10.2) base class of D, a program that
2311 // necessitates this conversion is ill-formed. The result of the
2312 // conversion is a pointer to the base class sub-object of the
2313 // derived class object. The null pointer value is converted to
2314 // the null pointer value of the destination type.
2315 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002316 // Note that we do not check for ambiguity or inaccessibility
2317 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002318 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002319 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002320 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002321 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002322 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002323 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002324 ToType, Context);
2325 return true;
2326 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002327
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002328 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2329 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2330 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2331 ToPointeeType,
2332 ToType, Context);
2333 return true;
2334 }
2335
Douglas Gregora119f102008-12-19 19:13:09 +00002336 return false;
2337}
Douglas Gregoraec25842011-04-26 23:16:46 +00002338
2339/// \brief Adopt the given qualifiers for the given type.
2340static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2341 Qualifiers TQs = T.getQualifiers();
2342
2343 // Check whether qualifiers already match.
2344 if (TQs == Qs)
2345 return T;
2346
2347 if (Qs.compatiblyIncludes(TQs))
2348 return Context.getQualifiedType(T, Qs);
2349
2350 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2351}
Douglas Gregora119f102008-12-19 19:13:09 +00002352
2353/// isObjCPointerConversion - Determines whether this is an
2354/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2355/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002356bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002357 QualType& ConvertedType,
2358 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002359 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002360 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002361
Douglas Gregoraec25842011-04-26 23:16:46 +00002362 // The set of qualifiers on the type we're converting from.
2363 Qualifiers FromQualifiers = FromType.getQualifiers();
2364
Steve Naroff7cae42b2009-07-10 23:34:53 +00002365 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002366 const ObjCObjectPointerType* ToObjCPtr =
2367 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002368 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002369 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002370
Steve Naroff7cae42b2009-07-10 23:34:53 +00002371 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002372 // If the pointee types are the same (ignoring qualifications),
2373 // then this is not a pointer conversion.
2374 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2375 FromObjCPtr->getPointeeType()))
2376 return false;
2377
Douglas Gregorab209d82015-07-07 03:58:42 +00002378 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002379 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002380 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2381 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002382 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002383 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2384 FromObjCPtr->getPointeeType()))
2385 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002386 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002387 ToObjCPtr->getPointeeType(),
2388 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002389 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002390 return true;
2391 }
2392
2393 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2394 // Okay: this is some kind of implicit downcast of Objective-C
2395 // interfaces, which is permitted. However, we're going to
2396 // complain about it.
2397 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002398 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002399 ToObjCPtr->getPointeeType(),
2400 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002401 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002402 return true;
2403 }
Mike Stump11289f42009-09-09 15:08:12 +00002404 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002405 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002406 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002407 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002408 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002409 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002410 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002411 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002412 // to a block pointer type.
2413 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002414 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002415 return true;
2416 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002417 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002418 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002419 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002420 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002421 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002422 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002423 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002424 return true;
2425 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002426 else
Douglas Gregora119f102008-12-19 19:13:09 +00002427 return false;
2428
Douglas Gregor033f56d2008-12-23 00:53:59 +00002429 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002430 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002431 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002432 else if (const BlockPointerType *FromBlockPtr =
2433 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002434 FromPointeeType = FromBlockPtr->getPointeeType();
2435 else
Douglas Gregora119f102008-12-19 19:13:09 +00002436 return false;
2437
Douglas Gregora119f102008-12-19 19:13:09 +00002438 // If we have pointers to pointers, recursively check whether this
2439 // is an Objective-C conversion.
2440 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2441 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2442 IncompatibleObjC)) {
2443 // We always complain about this conversion.
2444 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002445 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002446 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002447 return true;
2448 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002449 // Allow conversion of pointee being objective-c pointer to another one;
2450 // as in I* to id.
2451 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2452 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2453 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2454 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002455
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002456 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002457 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002458 return true;
2459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002460
Douglas Gregor033f56d2008-12-23 00:53:59 +00002461 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002462 // differences in the argument and result types are in Objective-C
2463 // pointer conversions. If so, we permit the conversion (but
2464 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002465 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002466 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002467 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002468 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002469 if (FromFunctionType && ToFunctionType) {
2470 // If the function types are exactly the same, this isn't an
2471 // Objective-C pointer conversion.
2472 if (Context.getCanonicalType(FromPointeeType)
2473 == Context.getCanonicalType(ToPointeeType))
2474 return false;
2475
2476 // Perform the quick checks that will tell us whether these
2477 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002478 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002479 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2480 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2481 return false;
2482
2483 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002484 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2485 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002486 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002487 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2488 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002489 ConvertedType, IncompatibleObjC)) {
2490 // Okay, we have an Objective-C pointer conversion.
2491 HasObjCConversion = true;
2492 } else {
2493 // Function types are too different. Abort.
2494 return false;
2495 }
Mike Stump11289f42009-09-09 15:08:12 +00002496
Douglas Gregora119f102008-12-19 19:13:09 +00002497 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002498 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002499 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002500 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2501 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002502 if (Context.getCanonicalType(FromArgType)
2503 == Context.getCanonicalType(ToArgType)) {
2504 // Okay, the types match exactly. Nothing to do.
2505 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2506 ConvertedType, IncompatibleObjC)) {
2507 // Okay, we have an Objective-C pointer conversion.
2508 HasObjCConversion = true;
2509 } else {
2510 // Argument types are too different. Abort.
2511 return false;
2512 }
2513 }
2514
2515 if (HasObjCConversion) {
2516 // We had an Objective-C conversion. Allow this pointer
2517 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002518 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002519 IncompatibleObjC = true;
2520 return true;
2521 }
2522 }
2523
Sebastian Redl72b597d2009-01-25 19:43:20 +00002524 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002525}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002526
John McCall31168b02011-06-15 23:02:42 +00002527/// \brief Determine whether this is an Objective-C writeback conversion,
2528/// used for parameter passing when performing automatic reference counting.
2529///
2530/// \param FromType The type we're converting form.
2531///
2532/// \param ToType The type we're converting to.
2533///
2534/// \param ConvertedType The type that will be produced after applying
2535/// this conversion.
2536bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2537 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002538 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002539 Context.hasSameUnqualifiedType(FromType, ToType))
2540 return false;
2541
2542 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2543 QualType ToPointee;
2544 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2545 ToPointee = ToPointer->getPointeeType();
2546 else
2547 return false;
2548
2549 Qualifiers ToQuals = ToPointee.getQualifiers();
2550 if (!ToPointee->isObjCLifetimeType() ||
2551 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002552 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002553 return false;
2554
2555 // Argument must be a pointer to __strong to __weak.
2556 QualType FromPointee;
2557 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2558 FromPointee = FromPointer->getPointeeType();
2559 else
2560 return false;
2561
2562 Qualifiers FromQuals = FromPointee.getQualifiers();
2563 if (!FromPointee->isObjCLifetimeType() ||
2564 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2565 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2566 return false;
2567
2568 // Make sure that we have compatible qualifiers.
2569 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2570 if (!ToQuals.compatiblyIncludes(FromQuals))
2571 return false;
2572
2573 // Remove qualifiers from the pointee type we're converting from; they
2574 // aren't used in the compatibility check belong, and we'll be adding back
2575 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2576 FromPointee = FromPointee.getUnqualifiedType();
2577
2578 // The unqualified form of the pointee types must be compatible.
2579 ToPointee = ToPointee.getUnqualifiedType();
2580 bool IncompatibleObjC;
2581 if (Context.typesAreCompatible(FromPointee, ToPointee))
2582 FromPointee = ToPointee;
2583 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2584 IncompatibleObjC))
2585 return false;
2586
2587 /// \brief Construct the type we're converting to, which is a pointer to
2588 /// __autoreleasing pointee.
2589 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2590 ConvertedType = Context.getPointerType(FromPointee);
2591 return true;
2592}
2593
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002594bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2595 QualType& ConvertedType) {
2596 QualType ToPointeeType;
2597 if (const BlockPointerType *ToBlockPtr =
2598 ToType->getAs<BlockPointerType>())
2599 ToPointeeType = ToBlockPtr->getPointeeType();
2600 else
2601 return false;
2602
2603 QualType FromPointeeType;
2604 if (const BlockPointerType *FromBlockPtr =
2605 FromType->getAs<BlockPointerType>())
2606 FromPointeeType = FromBlockPtr->getPointeeType();
2607 else
2608 return false;
2609 // We have pointer to blocks, check whether the only
2610 // differences in the argument and result types are in Objective-C
2611 // pointer conversions. If so, we permit the conversion.
2612
2613 const FunctionProtoType *FromFunctionType
2614 = FromPointeeType->getAs<FunctionProtoType>();
2615 const FunctionProtoType *ToFunctionType
2616 = ToPointeeType->getAs<FunctionProtoType>();
2617
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002618 if (!FromFunctionType || !ToFunctionType)
2619 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002620
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002621 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002622 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002623
2624 // Perform the quick checks that will tell us whether these
2625 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002626 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002627 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2628 return false;
2629
2630 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2631 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2632 if (FromEInfo != ToEInfo)
2633 return false;
2634
2635 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002636 if (Context.hasSameType(FromFunctionType->getReturnType(),
2637 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002638 // Okay, the types match exactly. Nothing to do.
2639 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002640 QualType RHS = FromFunctionType->getReturnType();
2641 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002642 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002643 !RHS.hasQualifiers() && LHS.hasQualifiers())
2644 LHS = LHS.getUnqualifiedType();
2645
2646 if (Context.hasSameType(RHS,LHS)) {
2647 // OK exact match.
2648 } else if (isObjCPointerConversion(RHS, LHS,
2649 ConvertedType, IncompatibleObjC)) {
2650 if (IncompatibleObjC)
2651 return false;
2652 // Okay, we have an Objective-C pointer conversion.
2653 }
2654 else
2655 return false;
2656 }
2657
2658 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002659 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002660 ArgIdx != NumArgs; ++ArgIdx) {
2661 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002662 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2663 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002664 if (Context.hasSameType(FromArgType, ToArgType)) {
2665 // Okay, the types match exactly. Nothing to do.
2666 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2667 ConvertedType, IncompatibleObjC)) {
2668 if (IncompatibleObjC)
2669 return false;
2670 // Okay, we have an Objective-C pointer conversion.
2671 } else
2672 // Argument types are too different. Abort.
2673 return false;
2674 }
John McCall18afab72016-03-01 00:49:02 +00002675 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2676 ToFunctionType))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002677 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002678
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002679 ConvertedType = ToType;
2680 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002681}
2682
Richard Trieucaff2472011-11-23 22:32:32 +00002683enum {
2684 ft_default,
2685 ft_different_class,
2686 ft_parameter_arity,
2687 ft_parameter_mismatch,
2688 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002689 ft_qualifer_mismatch,
2690 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002691};
2692
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002693/// Attempts to get the FunctionProtoType from a Type. Handles
2694/// MemberFunctionPointers properly.
2695static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2696 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2697 return FPT;
2698
2699 if (auto *MPT = FromType->getAs<MemberPointerType>())
2700 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2701
2702 return nullptr;
2703}
2704
Richard Trieucaff2472011-11-23 22:32:32 +00002705/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2706/// function types. Catches different number of parameter, mismatch in
2707/// parameter types, and different return types.
2708void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2709 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002710 // If either type is not valid, include no extra info.
2711 if (FromType.isNull() || ToType.isNull()) {
2712 PDiag << ft_default;
2713 return;
2714 }
2715
Richard Trieucaff2472011-11-23 22:32:32 +00002716 // Get the function type from the pointers.
2717 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2718 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2719 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002720 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002721 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2722 << QualType(FromMember->getClass(), 0);
2723 return;
2724 }
2725 FromType = FromMember->getPointeeType();
2726 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002727 }
2728
Richard Trieu96ed5b62011-12-13 23:19:45 +00002729 if (FromType->isPointerType())
2730 FromType = FromType->getPointeeType();
2731 if (ToType->isPointerType())
2732 ToType = ToType->getPointeeType();
2733
2734 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002735 FromType = FromType.getNonReferenceType();
2736 ToType = ToType.getNonReferenceType();
2737
Richard Trieucaff2472011-11-23 22:32:32 +00002738 // Don't print extra info for non-specialized template functions.
2739 if (FromType->isInstantiationDependentType() &&
2740 !FromType->getAs<TemplateSpecializationType>()) {
2741 PDiag << ft_default;
2742 return;
2743 }
2744
Richard Trieu96ed5b62011-12-13 23:19:45 +00002745 // No extra info for same types.
2746 if (Context.hasSameType(FromType, ToType)) {
2747 PDiag << ft_default;
2748 return;
2749 }
2750
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002751 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2752 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002753
2754 // Both types need to be function types.
2755 if (!FromFunction || !ToFunction) {
2756 PDiag << ft_default;
2757 return;
2758 }
2759
Alp Toker9cacbab2014-01-20 20:26:09 +00002760 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2761 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2762 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002763 return;
2764 }
2765
2766 // Handle different parameter types.
2767 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002768 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002769 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002770 << ToFunction->getParamType(ArgPos)
2771 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002772 return;
2773 }
2774
2775 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002776 if (!Context.hasSameType(FromFunction->getReturnType(),
2777 ToFunction->getReturnType())) {
2778 PDiag << ft_return_type << ToFunction->getReturnType()
2779 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002780 return;
2781 }
2782
2783 unsigned FromQuals = FromFunction->getTypeQuals(),
2784 ToQuals = ToFunction->getTypeQuals();
2785 if (FromQuals != ToQuals) {
2786 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2787 return;
2788 }
2789
Richard Smith3c4f8d22016-10-16 17:54:23 +00002790 // Handle exception specification differences on canonical type (in C++17
2791 // onwards).
2792 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2793 ->isNothrow(Context) !=
2794 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2795 ->isNothrow(Context)) {
2796 PDiag << ft_noexcept;
2797 return;
2798 }
2799
Richard Trieucaff2472011-11-23 22:32:32 +00002800 // Unable to find a difference, so add no extra info.
2801 PDiag << ft_default;
2802}
2803
Alp Toker9cacbab2014-01-20 20:26:09 +00002804/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002805/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002806/// they have same number of arguments. If the parameters are different,
2807/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002808bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2809 const FunctionProtoType *NewType,
2810 unsigned *ArgPos) {
2811 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2812 N = NewType->param_type_begin(),
2813 E = OldType->param_type_end();
2814 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002815 if (!Context.hasSameType(O->getUnqualifiedType(),
2816 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002817 if (ArgPos)
2818 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002819 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002820 }
2821 }
2822 return true;
2823}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002824
Douglas Gregor39c16d42008-10-24 04:54:22 +00002825/// CheckPointerConversion - Check the pointer conversion from the
2826/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002827/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002828/// conversions for which IsPointerConversion has already returned
2829/// true. It returns true and produces a diagnostic if there was an
2830/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002831bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002832 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002833 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002834 bool IgnoreBaseAccess,
2835 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002836 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002837 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002838
John McCall8cb679e2010-11-15 09:13:47 +00002839 Kind = CK_BitCast;
2840
George Burgess IV60bc9722016-01-13 23:36:34 +00002841 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002842 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002843 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002844 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2845 DiagRuntimeBehavior(From->getExprLoc(), From,
2846 PDiag(diag::warn_impcast_bool_to_null_pointer)
2847 << ToType << From->getSourceRange());
2848 else if (!isUnevaluatedContext())
2849 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2850 << ToType << From->getSourceRange();
2851 }
John McCall9320b872011-09-09 05:25:32 +00002852 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2853 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002854 QualType FromPointeeType = FromPtrType->getPointeeType(),
2855 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002856
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002857 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2858 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002859 // We must have a derived-to-base conversion. Check an
2860 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002861 unsigned InaccessibleID = 0;
2862 unsigned AmbigiousID = 0;
2863 if (Diagnose) {
2864 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2865 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2866 }
2867 if (CheckDerivedToBaseConversion(
2868 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2869 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2870 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002871 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002872
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002873 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002874 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002875 }
David Majnemer6bf02822015-10-31 08:42:14 +00002876
George Burgess IV60bc9722016-01-13 23:36:34 +00002877 if (Diagnose && !IsCStyleOrFunctionalCast &&
2878 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002879 assert(getLangOpts().MSVCCompat &&
2880 "this should only be possible with MSVCCompat!");
2881 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2882 << From->getSourceRange();
2883 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002884 }
John McCall9320b872011-09-09 05:25:32 +00002885 } else if (const ObjCObjectPointerType *ToPtrType =
2886 ToType->getAs<ObjCObjectPointerType>()) {
2887 if (const ObjCObjectPointerType *FromPtrType =
2888 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002889 // Objective-C++ conversions are always okay.
2890 // FIXME: We should have a different class of conversions for the
2891 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002892 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002893 return false;
John McCall9320b872011-09-09 05:25:32 +00002894 } else if (FromType->isBlockPointerType()) {
2895 Kind = CK_BlockPointerToObjCPointerCast;
2896 } else {
2897 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002898 }
John McCall9320b872011-09-09 05:25:32 +00002899 } else if (ToType->isBlockPointerType()) {
2900 if (!FromType->isBlockPointerType())
2901 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002902 }
John McCall8cb679e2010-11-15 09:13:47 +00002903
2904 // We shouldn't fall into this case unless it's valid for other
2905 // reasons.
2906 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2907 Kind = CK_NullToPointer;
2908
Douglas Gregor39c16d42008-10-24 04:54:22 +00002909 return false;
2910}
2911
Sebastian Redl72b597d2009-01-25 19:43:20 +00002912/// IsMemberPointerConversion - Determines whether the conversion of the
2913/// expression From, which has the (possibly adjusted) type FromType, can be
2914/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2915/// If so, returns true and places the converted type (that might differ from
2916/// ToType in its cv-qualifiers at some level) into ConvertedType.
2917bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002918 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002919 bool InOverloadResolution,
2920 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002921 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002922 if (!ToTypePtr)
2923 return false;
2924
2925 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002926 if (From->isNullPointerConstant(Context,
2927 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2928 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002929 ConvertedType = ToType;
2930 return true;
2931 }
2932
2933 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002934 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002935 if (!FromTypePtr)
2936 return false;
2937
2938 // A pointer to member of B can be converted to a pointer to member of D,
2939 // where D is derived from B (C++ 4.11p2).
2940 QualType FromClass(FromTypePtr->getClass(), 0);
2941 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002942
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002943 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002944 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002945 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2946 ToClass.getTypePtr());
2947 return true;
2948 }
2949
2950 return false;
2951}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952
Sebastian Redl72b597d2009-01-25 19:43:20 +00002953/// CheckMemberPointerConversion - Check the member pointer conversion from the
2954/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002955/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002956/// for which IsMemberPointerConversion has already returned true. It returns
2957/// true and produces a diagnostic if there was an error, or returns false
2958/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002959bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002960 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002961 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002962 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002963 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002964 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002965 if (!FromPtrType) {
2966 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002967 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002968 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002969 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002970 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002971 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002972 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002973
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002974 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002975 assert(ToPtrType && "No member pointer cast has a target type "
2976 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002977
Sebastian Redled8f2002009-01-28 18:33:18 +00002978 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2979 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002980
Sebastian Redled8f2002009-01-28 18:33:18 +00002981 // FIXME: What about dependent types?
2982 assert(FromClass->isRecordType() && "Pointer into non-class.");
2983 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002984
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002985 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002986 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002987 bool DerivationOkay =
2988 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002989 assert(DerivationOkay &&
2990 "Should not have been called if derivation isn't OK.");
2991 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002992
Sebastian Redled8f2002009-01-28 18:33:18 +00002993 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2994 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002995 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2996 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2997 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2998 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002999 }
Sebastian Redled8f2002009-01-28 18:33:18 +00003000
Douglas Gregor89ee6822009-02-28 01:32:25 +00003001 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00003002 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3003 << FromClass << ToClass << QualType(VBase, 0)
3004 << From->getSourceRange();
3005 return true;
3006 }
3007
John McCall5b0829a2010-02-10 09:31:12 +00003008 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00003009 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3010 Paths.front(),
3011 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00003012
Anders Carlssond7923c62009-08-22 23:33:40 +00003013 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003014 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00003015 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003016 return false;
3017}
3018
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003019/// Determine whether the lifetime conversion between the two given
3020/// qualifiers sets is nontrivial.
3021static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3022 Qualifiers ToQuals) {
3023 // Converting anything to const __unsafe_unretained is trivial.
3024 if (ToQuals.hasConst() &&
3025 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3026 return false;
3027
3028 return true;
3029}
3030
Douglas Gregor9a657932008-10-21 23:43:52 +00003031/// IsQualificationConversion - Determines whether the conversion from
3032/// an rvalue of type FromType to ToType is a qualification conversion
3033/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003034///
3035/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3036/// when the qualification conversion involves a change in the Objective-C
3037/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003038bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003039Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003040 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003041 FromType = Context.getCanonicalType(FromType);
3042 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003043 ObjCLifetimeConversion = false;
3044
Douglas Gregor9a657932008-10-21 23:43:52 +00003045 // If FromType and ToType are the same type, this is not a
3046 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003047 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003048 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003049
Douglas Gregor9a657932008-10-21 23:43:52 +00003050 // (C++ 4.4p4):
3051 // A conversion can add cv-qualifiers at levels other than the first
3052 // in multi-level pointers, subject to the following rules: [...]
3053 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003054 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003055 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003056 // Within each iteration of the loop, we check the qualifiers to
3057 // determine if this still looks like a qualification
3058 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003059 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003060 // until there are no more pointers or pointers-to-members left to
3061 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003062 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003063
Douglas Gregor90609aa2011-04-25 18:40:17 +00003064 Qualifiers FromQuals = FromType.getQualifiers();
3065 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003066
3067 // Ignore __unaligned qualifier if this type is void.
3068 if (ToType.getUnqualifiedType()->isVoidType())
3069 FromQuals.removeUnaligned();
Douglas Gregor90609aa2011-04-25 18:40:17 +00003070
John McCall31168b02011-06-15 23:02:42 +00003071 // Objective-C ARC:
3072 // Check Objective-C lifetime conversions.
3073 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3074 UnwrappedAnyPointer) {
3075 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003076 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3077 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003078 FromQuals.removeObjCLifetime();
3079 ToQuals.removeObjCLifetime();
3080 } else {
3081 // Qualification conversions cannot cast between different
3082 // Objective-C lifetime qualifiers.
3083 return false;
3084 }
3085 }
3086
Douglas Gregorf30053d2011-05-08 06:09:53 +00003087 // Allow addition/removal of GC attributes but not changing GC attributes.
3088 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3089 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3090 FromQuals.removeObjCGCAttr();
3091 ToQuals.removeObjCGCAttr();
3092 }
3093
Douglas Gregor9a657932008-10-21 23:43:52 +00003094 // -- for every j > 0, if const is in cv 1,j then const is in cv
3095 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003096 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003097 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003098
Douglas Gregor9a657932008-10-21 23:43:52 +00003099 // -- if the cv 1,j and cv 2,j are different, then const is in
3100 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003101 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003102 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003103 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003104
Douglas Gregor9a657932008-10-21 23:43:52 +00003105 // Keep track of whether all prior cv-qualifiers in the "to" type
3106 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003107 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003108 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003109 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003110
3111 // We are left with FromType and ToType being the pointee types
3112 // after unwrapping the original FromType and ToType the same number
3113 // of types. If we unwrapped any pointers, and if FromType and
3114 // ToType have the same unqualified type (since we checked
3115 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003116 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003117}
3118
Douglas Gregorc79862f2012-04-12 17:51:55 +00003119/// \brief - Determine whether this is a conversion from a scalar type to an
3120/// atomic type.
3121///
3122/// If successful, updates \c SCS's second and third steps in the conversion
3123/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003124static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3125 bool InOverloadResolution,
3126 StandardConversionSequence &SCS,
3127 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003128 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3129 if (!ToAtomic)
3130 return false;
3131
3132 StandardConversionSequence InnerSCS;
3133 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3134 InOverloadResolution, InnerSCS,
3135 CStyle, /*AllowObjCWritebackConversion=*/false))
3136 return false;
3137
3138 SCS.Second = InnerSCS.Second;
3139 SCS.setToType(1, InnerSCS.getToType(1));
3140 SCS.Third = InnerSCS.Third;
3141 SCS.QualificationIncludesObjCLifetime
3142 = InnerSCS.QualificationIncludesObjCLifetime;
3143 SCS.setToType(2, InnerSCS.getToType(2));
3144 return true;
3145}
3146
Sebastian Redle5417162012-03-27 18:33:03 +00003147static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3148 CXXConstructorDecl *Constructor,
3149 QualType Type) {
3150 const FunctionProtoType *CtorType =
3151 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003152 if (CtorType->getNumParams() > 0) {
3153 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003154 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3155 return true;
3156 }
3157 return false;
3158}
3159
Sebastian Redl82ace982012-02-11 23:51:08 +00003160static OverloadingResult
3161IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3162 CXXRecordDecl *To,
3163 UserDefinedConversionSequence &User,
3164 OverloadCandidateSet &CandidateSet,
3165 bool AllowExplicit) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003166 for (auto *D : S.LookupConstructors(To)) {
3167 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003168 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003169 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003170
Richard Smithc2bebe92016-05-11 20:37:46 +00003171 bool Usable = !Info.Constructor->isInvalidDecl() &&
3172 S.isInitListConstructor(Info.Constructor) &&
3173 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003174 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003175 // If the first argument is (a reference to) the target type,
3176 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003177 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3178 S.Context, Info.Constructor, ToType);
3179 if (Info.ConstructorTmpl)
3180 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3181 /*ExplicitArgs*/ nullptr, From,
3182 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003183 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003184 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3185 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003186 }
3187 }
3188
3189 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3190
3191 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003192 switch (auto Result =
3193 CandidateSet.BestViableFunction(S, From->getLocStart(),
3194 Best, true)) {
3195 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003196 case OR_Success: {
3197 // Record the standard conversion we used and the conversion function.
3198 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003199 QualType ThisType = Constructor->getThisType(S.Context);
3200 // Initializer lists don't have conversions as such.
3201 User.Before.setAsIdentityConversion();
3202 User.HadMultipleCandidates = HadMultipleCandidates;
3203 User.ConversionFunction = Constructor;
3204 User.FoundConversionFunction = Best->FoundDecl;
3205 User.After.setAsIdentityConversion();
3206 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3207 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003208 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003209 }
3210
3211 case OR_No_Viable_Function:
3212 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003213 case OR_Ambiguous:
3214 return OR_Ambiguous;
3215 }
3216
3217 llvm_unreachable("Invalid OverloadResult!");
3218}
3219
Douglas Gregor576e98c2009-01-30 23:27:23 +00003220/// Determines whether there is a user-defined conversion sequence
3221/// (C++ [over.ics.user]) that converts expression From to the type
3222/// ToType. If such a conversion exists, User will contain the
3223/// user-defined conversion sequence that performs such a conversion
3224/// and this routine will return true. Otherwise, this routine returns
3225/// false and User is unspecified.
3226///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003227/// \param AllowExplicit true if the conversion should consider C++0x
3228/// "explicit" conversion functions as well as non-explicit conversion
3229/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003230///
3231/// \param AllowObjCConversionOnExplicit true if the conversion should
3232/// allow an extra Objective-C pointer conversion on uses of explicit
3233/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003234static OverloadingResult
3235IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003236 UserDefinedConversionSequence &User,
3237 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003238 bool AllowExplicit,
3239 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003240 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003241
Douglas Gregor5ab11652010-04-17 22:01:05 +00003242 // Whether we will only visit constructors.
3243 bool ConstructorsOnly = false;
3244
3245 // If the type we are conversion to is a class type, enumerate its
3246 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003247 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003248 // C++ [over.match.ctor]p1:
3249 // When objects of class type are direct-initialized (8.5), or
3250 // copy-initialized from an expression of the same or a
3251 // derived class type (8.5), overload resolution selects the
3252 // constructor. [...] For copy-initialization, the candidate
3253 // functions are all the converting constructors (12.3.1) of
3254 // that class. The argument list is the expression-list within
3255 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003256 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003257 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003258 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003259 ConstructorsOnly = true;
3260
Richard Smithdb0ac552015-12-18 22:40:25 +00003261 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003262 // We're not going to find any constructors.
3263 } else if (CXXRecordDecl *ToRecordDecl
3264 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003265
3266 Expr **Args = &From;
3267 unsigned NumArgs = 1;
3268 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003269 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003270 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003271 OverloadingResult Result = IsInitializerListConstructorConversion(
3272 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3273 if (Result != OR_No_Viable_Function)
3274 return Result;
3275 // Never mind.
3276 CandidateSet.clear();
3277
3278 // If we're list-initializing, we pass the individual elements as
3279 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003280 Args = InitList->getInits();
3281 NumArgs = InitList->getNumInits();
3282 ListInitializing = true;
3283 }
3284
Richard Smithc2bebe92016-05-11 20:37:46 +00003285 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3286 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003287 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003288 continue;
John McCalla0296f72010-03-19 07:35:19 +00003289
Richard Smithc2bebe92016-05-11 20:37:46 +00003290 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003291 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003292 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003293 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003294 Usable = Usable &&
3295 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003296 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003297 bool SuppressUserConversions = !ConstructorsOnly;
3298 if (SuppressUserConversions && ListInitializing) {
3299 SuppressUserConversions = false;
3300 if (NumArgs == 1) {
3301 // If the first argument is (a reference to) the target type,
3302 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003303 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003304 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003305 }
3306 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003307 if (Info.ConstructorTmpl)
3308 S.AddTemplateOverloadCandidate(
3309 Info.ConstructorTmpl, Info.FoundDecl,
3310 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3311 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003312 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003313 // Allow one user-defined conversion when user specifies a
3314 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003315 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003316 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003317 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003318 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003319 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003320 }
3321 }
3322
Douglas Gregor5ab11652010-04-17 22:01:05 +00003323 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003324 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003325 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003326 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003327 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003328 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003329 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003330 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3331 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003332 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3333 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003334 DeclAccessPair FoundDecl = I.getPair();
3335 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003336 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3337 if (isa<UsingShadowDecl>(D))
3338 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3339
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003340 CXXConversionDecl *Conv;
3341 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003342 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3343 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003344 else
John McCallda4458e2010-03-31 01:36:47 +00003345 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003346
3347 if (AllowExplicit || !Conv->isExplicit()) {
3348 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003349 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3350 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003351 CandidateSet,
3352 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003353 else
John McCall5c32be02010-08-24 20:38:10 +00003354 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003355 From, ToType, CandidateSet,
3356 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003357 }
3358 }
3359 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003360 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003361
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003362 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3363
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003364 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003365 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3366 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003367 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003368 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003369 // Record the standard conversion we used and the conversion function.
3370 if (CXXConstructorDecl *Constructor
3371 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3372 // C++ [over.ics.user]p1:
3373 // If the user-defined conversion is specified by a
3374 // constructor (12.3.1), the initial standard conversion
3375 // sequence converts the source type to the type required by
3376 // the argument of the constructor.
3377 //
3378 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003379 if (isa<InitListExpr>(From)) {
3380 // Initializer lists don't have conversions as such.
3381 User.Before.setAsIdentityConversion();
3382 } else {
3383 if (Best->Conversions[0].isEllipsis())
3384 User.EllipsisConversion = true;
3385 else {
3386 User.Before = Best->Conversions[0].Standard;
3387 User.EllipsisConversion = false;
3388 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003389 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003390 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003391 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003392 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003393 User.After.setAsIdentityConversion();
3394 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3395 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003396 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003397 }
3398 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003399 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3400 // C++ [over.ics.user]p1:
3401 //
3402 // [...] If the user-defined conversion is specified by a
3403 // conversion function (12.3.2), the initial standard
3404 // conversion sequence converts the source type to the
3405 // implicit object parameter of the conversion function.
3406 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003407 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003408 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003409 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003410 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003411
John McCall5c32be02010-08-24 20:38:10 +00003412 // C++ [over.ics.user]p2:
3413 // The second standard conversion sequence converts the
3414 // result of the user-defined conversion to the target type
3415 // for the sequence. Since an implicit conversion sequence
3416 // is an initialization, the special rules for
3417 // initialization by user-defined conversion apply when
3418 // selecting the best user-defined conversion for a
3419 // user-defined conversion sequence (see 13.3.3 and
3420 // 13.3.3.1).
3421 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003422 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003423 }
David Blaikie8a40f702012-01-17 06:56:22 +00003424 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003425
John McCall5c32be02010-08-24 20:38:10 +00003426 case OR_No_Viable_Function:
3427 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428
John McCall5c32be02010-08-24 20:38:10 +00003429 case OR_Ambiguous:
3430 return OR_Ambiguous;
3431 }
3432
David Blaikie8a40f702012-01-17 06:56:22 +00003433 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003434}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003436bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003437Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003438 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003439 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3440 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003441 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003442 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003443 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003444 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003445 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3446 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003447 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003448 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003449 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003450 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003451 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003452 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003453 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003454 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003455 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003457}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003458
Douglas Gregor2837aa22012-02-22 17:32:19 +00003459/// \brief Compare the user-defined conversion functions or constructors
3460/// of two user-defined conversion sequences to determine whether any ordering
3461/// is possible.
3462static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003463compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003464 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003465 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003466 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003467
Douglas Gregor2837aa22012-02-22 17:32:19 +00003468 // Objective-C++:
3469 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003470 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003471 // respectively, always prefer the conversion to a function pointer,
3472 // because the function pointer is more lightweight and is more likely
3473 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003474 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003475 if (!Conv1)
3476 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003477
Douglas Gregor2837aa22012-02-22 17:32:19 +00003478 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3479 if (!Conv2)
3480 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003481
Douglas Gregor2837aa22012-02-22 17:32:19 +00003482 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3483 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3484 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3485 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003486 return Block1 ? ImplicitConversionSequence::Worse
3487 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003488 }
3489
3490 return ImplicitConversionSequence::Indistinguishable;
3491}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003492
3493static bool hasDeprecatedStringLiteralToCharPtrConversion(
3494 const ImplicitConversionSequence &ICS) {
3495 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3496 (ICS.isUserDefined() &&
3497 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3498}
3499
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003500/// CompareImplicitConversionSequences - Compare two implicit
3501/// conversion sequences to determine whether one is better than the
3502/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003503static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003504CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003505 const ImplicitConversionSequence& ICS1,
3506 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003507{
3508 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3509 // conversion sequences (as defined in 13.3.3.1)
3510 // -- a standard conversion sequence (13.3.3.1.1) is a better
3511 // conversion sequence than a user-defined conversion sequence or
3512 // an ellipsis conversion sequence, and
3513 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3514 // conversion sequence than an ellipsis conversion sequence
3515 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003516 //
John McCall0d1da222010-01-12 00:44:57 +00003517 // C++0x [over.best.ics]p10:
3518 // For the purpose of ranking implicit conversion sequences as
3519 // described in 13.3.3.2, the ambiguous conversion sequence is
3520 // treated as a user-defined sequence that is indistinguishable
3521 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003522
3523 // String literal to 'char *' conversion has been deprecated in C++03. It has
3524 // been removed from C++11. We still accept this conversion, if it happens at
3525 // the best viable function. Otherwise, this conversion is considered worse
3526 // than ellipsis conversion. Consider this as an extension; this is not in the
3527 // standard. For example:
3528 //
3529 // int &f(...); // #1
3530 // void f(char*); // #2
3531 // void g() { int &r = f("foo"); }
3532 //
3533 // In C++03, we pick #2 as the best viable function.
3534 // In C++11, we pick #1 as the best viable function, because ellipsis
3535 // conversion is better than string-literal to char* conversion (since there
3536 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3537 // convert arguments, #2 would be the best viable function in C++11.
3538 // If the best viable function has this conversion, a warning will be issued
3539 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3540
3541 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3542 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3543 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3544 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3545 ? ImplicitConversionSequence::Worse
3546 : ImplicitConversionSequence::Better;
3547
Douglas Gregor5ab11652010-04-17 22:01:05 +00003548 if (ICS1.getKindRank() < ICS2.getKindRank())
3549 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003550 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003551 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003552
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003553 // The following checks require both conversion sequences to be of
3554 // the same kind.
3555 if (ICS1.getKind() != ICS2.getKind())
3556 return ImplicitConversionSequence::Indistinguishable;
3557
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003558 ImplicitConversionSequence::CompareKind Result =
3559 ImplicitConversionSequence::Indistinguishable;
3560
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003561 // Two implicit conversion sequences of the same form are
3562 // indistinguishable conversion sequences unless one of the
3563 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003564
3565 // List-initialization sequence L1 is a better conversion sequence than
3566 // list-initialization sequence L2 if:
3567 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3568 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003569 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003570 // and N1 is smaller than N2.,
3571 // even if one of the other rules in this paragraph would otherwise apply.
3572 if (!ICS1.isBad()) {
3573 if (ICS1.isStdInitializerListElement() &&
3574 !ICS2.isStdInitializerListElement())
3575 return ImplicitConversionSequence::Better;
3576 if (!ICS1.isStdInitializerListElement() &&
3577 ICS2.isStdInitializerListElement())
3578 return ImplicitConversionSequence::Worse;
3579 }
3580
John McCall0d1da222010-01-12 00:44:57 +00003581 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003582 // Standard conversion sequence S1 is a better conversion sequence than
3583 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003584 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003585 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003586 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003587 // User-defined conversion sequence U1 is a better conversion
3588 // sequence than another user-defined conversion sequence U2 if
3589 // they contain the same user-defined conversion function or
3590 // constructor and if the second standard conversion sequence of
3591 // U1 is better than the second standard conversion sequence of
3592 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003593 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003594 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003595 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003596 ICS1.UserDefined.After,
3597 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003598 else
3599 Result = compareConversionFunctions(S,
3600 ICS1.UserDefined.ConversionFunction,
3601 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003602 }
3603
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003604 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003605}
3606
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003607static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3608 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3609 Qualifiers Quals;
3610 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003611 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003612 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003613
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003614 return Context.hasSameUnqualifiedType(T1, T2);
3615}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003616
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003617// Per 13.3.3.2p3, compare the given standard conversion sequences to
3618// determine if one is a proper subset of the other.
3619static ImplicitConversionSequence::CompareKind
3620compareStandardConversionSubsets(ASTContext &Context,
3621 const StandardConversionSequence& SCS1,
3622 const StandardConversionSequence& SCS2) {
3623 ImplicitConversionSequence::CompareKind Result
3624 = ImplicitConversionSequence::Indistinguishable;
3625
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003626 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003627 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003628 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3629 return ImplicitConversionSequence::Better;
3630 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3631 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003632
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003633 if (SCS1.Second != SCS2.Second) {
3634 if (SCS1.Second == ICK_Identity)
3635 Result = ImplicitConversionSequence::Better;
3636 else if (SCS2.Second == ICK_Identity)
3637 Result = ImplicitConversionSequence::Worse;
3638 else
3639 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003640 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003641 return ImplicitConversionSequence::Indistinguishable;
3642
3643 if (SCS1.Third == SCS2.Third) {
3644 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3645 : ImplicitConversionSequence::Indistinguishable;
3646 }
3647
3648 if (SCS1.Third == ICK_Identity)
3649 return Result == ImplicitConversionSequence::Worse
3650 ? ImplicitConversionSequence::Indistinguishable
3651 : ImplicitConversionSequence::Better;
3652
3653 if (SCS2.Third == ICK_Identity)
3654 return Result == ImplicitConversionSequence::Better
3655 ? ImplicitConversionSequence::Indistinguishable
3656 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003657
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003658 return ImplicitConversionSequence::Indistinguishable;
3659}
3660
Douglas Gregore696ebb2011-01-26 14:52:12 +00003661/// \brief Determine whether one of the given reference bindings is better
3662/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003663static bool
3664isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3665 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003666 // C++0x [over.ics.rank]p3b4:
3667 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3668 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003669 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003670 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003672 // reference*.
3673 //
3674 // FIXME: Rvalue references. We're going rogue with the above edits,
3675 // because the semantics in the current C++0x working paper (N3225 at the
3676 // time of this writing) break the standard definition of std::forward
3677 // and std::reference_wrapper when dealing with references to functions.
3678 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003679 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3680 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3681 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003682
Douglas Gregore696ebb2011-01-26 14:52:12 +00003683 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3684 SCS2.IsLvalueReference) ||
3685 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003686 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003687}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003688
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003689/// CompareStandardConversionSequences - Compare two standard
3690/// conversion sequences to determine whether one is better than the
3691/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003692static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003693CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003694 const StandardConversionSequence& SCS1,
3695 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003696{
3697 // Standard conversion sequence S1 is a better conversion sequence
3698 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3699
3700 // -- S1 is a proper subsequence of S2 (comparing the conversion
3701 // sequences in the canonical form defined by 13.3.3.1.1,
3702 // excluding any Lvalue Transformation; the identity conversion
3703 // sequence is considered to be a subsequence of any
3704 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003705 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003706 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003707 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003708
3709 // -- the rank of S1 is better than the rank of S2 (by the rules
3710 // defined below), or, if not that,
3711 ImplicitConversionRank Rank1 = SCS1.getRank();
3712 ImplicitConversionRank Rank2 = SCS2.getRank();
3713 if (Rank1 < Rank2)
3714 return ImplicitConversionSequence::Better;
3715 else if (Rank2 < Rank1)
3716 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003717
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003718 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3719 // are indistinguishable unless one of the following rules
3720 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003721
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003722 // A conversion that is not a conversion of a pointer, or
3723 // pointer to member, to bool is better than another conversion
3724 // that is such a conversion.
3725 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3726 return SCS2.isPointerConversionToBool()
3727 ? ImplicitConversionSequence::Better
3728 : ImplicitConversionSequence::Worse;
3729
Douglas Gregor5c407d92008-10-23 00:40:37 +00003730 // C++ [over.ics.rank]p4b2:
3731 //
3732 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003733 // conversion of B* to A* is better than conversion of B* to
3734 // void*, and conversion of A* to void* is better than conversion
3735 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003736 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003737 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003738 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003739 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003740 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3741 // Exactly one of the conversion sequences is a conversion to
3742 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003743 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3744 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003745 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3746 // Neither conversion sequence converts to a void pointer; compare
3747 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003748 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003749 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003750 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003751 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3752 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003753 // Both conversion sequences are conversions to void
3754 // pointers. Compare the source types to determine if there's an
3755 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003756 QualType FromType1 = SCS1.getFromType();
3757 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003758
3759 // Adjust the types we're converting from via the array-to-pointer
3760 // conversion, if we need to.
3761 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003762 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003763 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003764 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003765
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003766 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3767 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003768
Richard Smith0f59cb32015-12-18 21:45:41 +00003769 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003770 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003771 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003772 return ImplicitConversionSequence::Worse;
3773
3774 // Objective-C++: If one interface is more specific than the
3775 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003776 const ObjCObjectPointerType* FromObjCPtr1
3777 = FromType1->getAs<ObjCObjectPointerType>();
3778 const ObjCObjectPointerType* FromObjCPtr2
3779 = FromType2->getAs<ObjCObjectPointerType>();
3780 if (FromObjCPtr1 && FromObjCPtr2) {
3781 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3782 FromObjCPtr2);
3783 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3784 FromObjCPtr1);
3785 if (AssignLeft != AssignRight) {
3786 return AssignLeft? ImplicitConversionSequence::Better
3787 : ImplicitConversionSequence::Worse;
3788 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003789 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003790 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003791
3792 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3793 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003794 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003795 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003796 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003797
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003798 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003799 // Check for a better reference binding based on the kind of bindings.
3800 if (isBetterReferenceBindingKind(SCS1, SCS2))
3801 return ImplicitConversionSequence::Better;
3802 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3803 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003804
Sebastian Redlb28b4072009-03-22 23:49:27 +00003805 // C++ [over.ics.rank]p3b4:
3806 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3807 // which the references refer are the same type except for
3808 // top-level cv-qualifiers, and the type to which the reference
3809 // initialized by S2 refers is more cv-qualified than the type
3810 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003811 QualType T1 = SCS1.getToType(2);
3812 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003813 T1 = S.Context.getCanonicalType(T1);
3814 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003815 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003816 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3817 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003818 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003819 // Objective-C++ ARC: If the references refer to objects with different
3820 // lifetimes, prefer bindings that don't change lifetime.
3821 if (SCS1.ObjCLifetimeConversionBinding !=
3822 SCS2.ObjCLifetimeConversionBinding) {
3823 return SCS1.ObjCLifetimeConversionBinding
3824 ? ImplicitConversionSequence::Worse
3825 : ImplicitConversionSequence::Better;
3826 }
3827
Chandler Carruth8e543b32010-12-12 08:17:55 +00003828 // If the type is an array type, promote the element qualifiers to the
3829 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003830 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003831 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003832 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003833 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003834 if (T2.isMoreQualifiedThan(T1))
3835 return ImplicitConversionSequence::Better;
3836 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003837 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003838 }
3839 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003840
Francois Pichet08d2fa02011-09-18 21:37:37 +00003841 // In Microsoft mode, prefer an integral conversion to a
3842 // floating-to-integral conversion if the integral conversion
3843 // is between types of the same size.
3844 // For example:
3845 // void f(float);
3846 // void f(int);
3847 // int main {
3848 // long a;
3849 // f(a);
3850 // }
3851 // Here, MSVC will call f(int) instead of generating a compile error
3852 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003853 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3854 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003855 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003856 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003857 return ImplicitConversionSequence::Better;
3858
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003859 return ImplicitConversionSequence::Indistinguishable;
3860}
3861
3862/// CompareQualificationConversions - Compares two standard conversion
3863/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003864/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003865static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003866CompareQualificationConversions(Sema &S,
3867 const StandardConversionSequence& SCS1,
3868 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003869 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003870 // -- S1 and S2 differ only in their qualification conversion and
3871 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3872 // cv-qualification signature of type T1 is a proper subset of
3873 // the cv-qualification signature of type T2, and S1 is not the
3874 // deprecated string literal array-to-pointer conversion (4.2).
3875 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3876 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3877 return ImplicitConversionSequence::Indistinguishable;
3878
3879 // FIXME: the example in the standard doesn't use a qualification
3880 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003881 QualType T1 = SCS1.getToType(2);
3882 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003883 T1 = S.Context.getCanonicalType(T1);
3884 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003885 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003886 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3887 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003888
3889 // If the types are the same, we won't learn anything by unwrapped
3890 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003891 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003892 return ImplicitConversionSequence::Indistinguishable;
3893
Chandler Carruth607f38e2009-12-29 07:16:59 +00003894 // If the type is an array type, promote the element qualifiers to the type
3895 // for comparison.
3896 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003897 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003898 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003899 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003900
Mike Stump11289f42009-09-09 15:08:12 +00003901 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003902 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003903
3904 // Objective-C++ ARC:
3905 // Prefer qualification conversions not involving a change in lifetime
3906 // to qualification conversions that do not change lifetime.
3907 if (SCS1.QualificationIncludesObjCLifetime !=
3908 SCS2.QualificationIncludesObjCLifetime) {
3909 Result = SCS1.QualificationIncludesObjCLifetime
3910 ? ImplicitConversionSequence::Worse
3911 : ImplicitConversionSequence::Better;
3912 }
3913
John McCall5c32be02010-08-24 20:38:10 +00003914 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003915 // Within each iteration of the loop, we check the qualifiers to
3916 // determine if this still looks like a qualification
3917 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003918 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003919 // until there are no more pointers or pointers-to-members left
3920 // to unwrap. This essentially mimics what
3921 // IsQualificationConversion does, but here we're checking for a
3922 // strict subset of qualifiers.
3923 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3924 // The qualifiers are the same, so this doesn't tell us anything
3925 // about how the sequences rank.
3926 ;
3927 else if (T2.isMoreQualifiedThan(T1)) {
3928 // T1 has fewer qualifiers, so it could be the better sequence.
3929 if (Result == ImplicitConversionSequence::Worse)
3930 // Neither has qualifiers that are a subset of the other's
3931 // qualifiers.
3932 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003933
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003934 Result = ImplicitConversionSequence::Better;
3935 } else if (T1.isMoreQualifiedThan(T2)) {
3936 // T2 has fewer qualifiers, so it could be the better sequence.
3937 if (Result == ImplicitConversionSequence::Better)
3938 // Neither has qualifiers that are a subset of the other's
3939 // qualifiers.
3940 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003941
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003942 Result = ImplicitConversionSequence::Worse;
3943 } else {
3944 // Qualifiers are disjoint.
3945 return ImplicitConversionSequence::Indistinguishable;
3946 }
3947
3948 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003949 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003950 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003951 }
3952
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003953 // Check that the winning standard conversion sequence isn't using
3954 // the deprecated string literal array to pointer conversion.
3955 switch (Result) {
3956 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003957 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003958 Result = ImplicitConversionSequence::Indistinguishable;
3959 break;
3960
3961 case ImplicitConversionSequence::Indistinguishable:
3962 break;
3963
3964 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003965 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003966 Result = ImplicitConversionSequence::Indistinguishable;
3967 break;
3968 }
3969
3970 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003971}
3972
Douglas Gregor5c407d92008-10-23 00:40:37 +00003973/// CompareDerivedToBaseConversions - Compares two standard conversion
3974/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003975/// various kinds of derived-to-base conversions (C++
3976/// [over.ics.rank]p4b3). As part of these checks, we also look at
3977/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003978static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003979CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003980 const StandardConversionSequence& SCS1,
3981 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003982 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003983 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003984 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003985 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003986
3987 // Adjust the types we're converting from via the array-to-pointer
3988 // conversion, if we need to.
3989 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003990 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003991 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003992 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003993
3994 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003995 FromType1 = S.Context.getCanonicalType(FromType1);
3996 ToType1 = S.Context.getCanonicalType(ToType1);
3997 FromType2 = S.Context.getCanonicalType(FromType2);
3998 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003999
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004000 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00004001 //
4002 // If class B is derived directly or indirectly from class A and
4003 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00004004 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004005 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00004006 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00004007 SCS2.Second == ICK_Pointer_Conversion &&
4008 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4009 FromType1->isPointerType() && FromType2->isPointerType() &&
4010 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004011 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004012 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00004013 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004014 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004015 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004016 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004017 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004018 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004019
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004020 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004021 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004022 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004023 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004024 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004025 return ImplicitConversionSequence::Worse;
4026 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004027
4028 // -- conversion of B* to A* is better than conversion of C* to A*,
4029 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004030 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004031 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004032 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004033 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004034 }
4035 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4036 SCS2.Second == ICK_Pointer_Conversion) {
4037 const ObjCObjectPointerType *FromPtr1
4038 = FromType1->getAs<ObjCObjectPointerType>();
4039 const ObjCObjectPointerType *FromPtr2
4040 = FromType2->getAs<ObjCObjectPointerType>();
4041 const ObjCObjectPointerType *ToPtr1
4042 = ToType1->getAs<ObjCObjectPointerType>();
4043 const ObjCObjectPointerType *ToPtr2
4044 = ToType2->getAs<ObjCObjectPointerType>();
4045
4046 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4047 // Apply the same conversion ranking rules for Objective-C pointer types
4048 // that we do for C++ pointers to class types. However, we employ the
4049 // Objective-C pseudo-subtyping relationship used for assignment of
4050 // Objective-C pointer types.
4051 bool FromAssignLeft
4052 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4053 bool FromAssignRight
4054 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4055 bool ToAssignLeft
4056 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4057 bool ToAssignRight
4058 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4059
4060 // A conversion to an a non-id object pointer type or qualified 'id'
4061 // type is better than a conversion to 'id'.
4062 if (ToPtr1->isObjCIdType() &&
4063 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4064 return ImplicitConversionSequence::Worse;
4065 if (ToPtr2->isObjCIdType() &&
4066 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4067 return ImplicitConversionSequence::Better;
4068
4069 // A conversion to a non-id object pointer type is better than a
4070 // conversion to a qualified 'id' type
4071 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4072 return ImplicitConversionSequence::Worse;
4073 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4074 return ImplicitConversionSequence::Better;
4075
4076 // A conversion to an a non-Class object pointer type or qualified 'Class'
4077 // type is better than a conversion to 'Class'.
4078 if (ToPtr1->isObjCClassType() &&
4079 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4080 return ImplicitConversionSequence::Worse;
4081 if (ToPtr2->isObjCClassType() &&
4082 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4083 return ImplicitConversionSequence::Better;
4084
4085 // A conversion to a non-Class object pointer type is better than a
4086 // conversion to a qualified 'Class' type.
4087 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4088 return ImplicitConversionSequence::Worse;
4089 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4090 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004091
Douglas Gregor058d3de2011-01-31 18:51:41 +00004092 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4093 if (S.Context.hasSameType(FromType1, FromType2) &&
4094 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4095 (ToAssignLeft != ToAssignRight))
4096 return ToAssignLeft? ImplicitConversionSequence::Worse
4097 : ImplicitConversionSequence::Better;
4098
4099 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4100 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4101 (FromAssignLeft != FromAssignRight))
4102 return FromAssignLeft? ImplicitConversionSequence::Better
4103 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004104 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004105 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004106
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004107 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004108 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4109 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4110 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004111 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004112 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004113 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004114 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004115 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004116 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004117 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004118 ToType2->getAs<MemberPointerType>();
4119 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4120 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4121 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4122 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4123 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4124 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4125 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4126 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004127 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004128 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004129 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004130 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004131 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004132 return ImplicitConversionSequence::Better;
4133 }
4134 // conversion of B::* to C::* is better than conversion of A::* to C::*
4135 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004136 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004137 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004138 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004139 return ImplicitConversionSequence::Worse;
4140 }
4141 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004142
Douglas Gregor5ab11652010-04-17 22:01:05 +00004143 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004144 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004145 // -- binding of an expression of type C to a reference of type
4146 // B& is better than binding an expression of type C to a
4147 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004148 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4149 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004150 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004151 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004152 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004153 return ImplicitConversionSequence::Worse;
4154 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004155
Douglas Gregor2fe98832008-11-03 19:09:14 +00004156 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004157 // -- binding of an expression of type B to a reference of type
4158 // A& is better than binding an expression of type C to a
4159 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004160 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4161 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004162 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004163 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004164 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004165 return ImplicitConversionSequence::Worse;
4166 }
4167 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004168
Douglas Gregor5c407d92008-10-23 00:40:37 +00004169 return ImplicitConversionSequence::Indistinguishable;
4170}
4171
Douglas Gregor45bb4832013-03-26 23:36:30 +00004172/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4173/// C++ class.
4174static bool isTypeValid(QualType T) {
4175 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4176 return !Record->isInvalidDecl();
4177
4178 return true;
4179}
4180
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004181/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4182/// determine whether they are reference-related,
4183/// reference-compatible, reference-compatible with added
4184/// qualification, or incompatible, for use in C++ initialization by
4185/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4186/// type, and the first type (T1) is the pointee type of the reference
4187/// type being initialized.
4188Sema::ReferenceCompareResult
4189Sema::CompareReferenceRelationship(SourceLocation Loc,
4190 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004191 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004192 bool &ObjCConversion,
4193 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004194 assert(!OrigT1->isReferenceType() &&
4195 "T1 must be the pointee type of the reference type");
4196 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4197
4198 QualType T1 = Context.getCanonicalType(OrigT1);
4199 QualType T2 = Context.getCanonicalType(OrigT2);
4200 Qualifiers T1Quals, T2Quals;
4201 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4202 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4203
4204 // C++ [dcl.init.ref]p4:
4205 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4206 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4207 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004208 DerivedToBase = false;
4209 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004210 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004211 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004212 if (UnqualT1 == UnqualT2) {
4213 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004214 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004215 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004216 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004217 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004218 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4219 UnqualT2->isObjCObjectOrInterfaceType() &&
4220 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4221 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004222 else if (UnqualT2->isFunctionType() &&
4223 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4224 // C++1z [dcl.init.ref]p4:
4225 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4226 // function" and T1 is "function"
4227 //
4228 // We extend this to also apply to 'noreturn', so allow any function
4229 // conversion between function types.
4230 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004231 else
4232 return Ref_Incompatible;
4233
4234 // At this point, we know that T1 and T2 are reference-related (at
4235 // least).
4236
4237 // If the type is an array type, promote the element qualifiers to the type
4238 // for comparison.
4239 if (isa<ArrayType>(T1) && T1Quals)
4240 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4241 if (isa<ArrayType>(T2) && T2Quals)
4242 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4243
4244 // C++ [dcl.init.ref]p4:
4245 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4246 // reference-related to T2 and cv1 is the same cv-qualification
4247 // as, or greater cv-qualification than, cv2. For purposes of
4248 // overload resolution, cases for which cv1 is greater
4249 // cv-qualification than cv2 are identified as
4250 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004251 //
4252 // Note that we also require equivalence of Objective-C GC and address-space
4253 // qualifiers when performing these computations, so that e.g., an int in
4254 // address space 1 is not reference-compatible with an int in address
4255 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004256 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4257 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004258 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4259 ObjCLifetimeConversion = true;
4260
John McCall31168b02011-06-15 23:02:42 +00004261 T1Quals.removeObjCLifetime();
4262 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004263 }
4264
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004265 // MS compiler ignores __unaligned qualifier for references; do the same.
4266 T1Quals.removeUnaligned();
4267 T2Quals.removeUnaligned();
4268
Richard Smithce766292016-10-21 23:01:55 +00004269 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004270 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004271 else
4272 return Ref_Related;
4273}
4274
Douglas Gregor836a7e82010-08-11 02:15:33 +00004275/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004276/// with DeclType. Return true if something definite is found.
4277static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004278FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4279 QualType DeclType, SourceLocation DeclLoc,
4280 Expr *Init, QualType T2, bool AllowRvalues,
4281 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004282 assert(T2->isRecordType() && "Can only find conversions of record types.");
4283 CXXRecordDecl *T2RecordDecl
4284 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4285
Richard Smith100b24a2014-04-17 01:52:14 +00004286 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004287 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4288 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004289 NamedDecl *D = *I;
4290 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4291 if (isa<UsingShadowDecl>(D))
4292 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4293
4294 FunctionTemplateDecl *ConvTemplate
4295 = dyn_cast<FunctionTemplateDecl>(D);
4296 CXXConversionDecl *Conv;
4297 if (ConvTemplate)
4298 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4299 else
4300 Conv = cast<CXXConversionDecl>(D);
4301
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004303 // explicit conversions, skip it.
4304 if (!AllowExplicit && Conv->isExplicit())
4305 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306
Douglas Gregor836a7e82010-08-11 02:15:33 +00004307 if (AllowRvalues) {
4308 bool DerivedToBase = false;
4309 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004310 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004311
4312 // If we are initializing an rvalue reference, don't permit conversion
4313 // functions that return lvalues.
4314 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4315 const ReferenceType *RefType
4316 = Conv->getConversionType()->getAs<LValueReferenceType>();
4317 if (RefType && !RefType->getPointeeType()->isFunctionType())
4318 continue;
4319 }
4320
Douglas Gregor836a7e82010-08-11 02:15:33 +00004321 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004322 S.CompareReferenceRelationship(
4323 DeclLoc,
4324 Conv->getConversionType().getNonReferenceType()
4325 .getUnqualifiedType(),
4326 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004327 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004328 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004329 continue;
4330 } else {
4331 // If the conversion function doesn't return a reference type,
4332 // it can't be considered for this conversion. An rvalue reference
4333 // is only acceptable if its referencee is a function type.
4334
4335 const ReferenceType *RefType =
4336 Conv->getConversionType()->getAs<ReferenceType>();
4337 if (!RefType ||
4338 (!RefType->isLValueReferenceType() &&
4339 !RefType->getPointeeType()->isFunctionType()))
4340 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004341 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004342
Douglas Gregor836a7e82010-08-11 02:15:33 +00004343 if (ConvTemplate)
4344 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004345 Init, DeclType, CandidateSet,
4346 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004347 else
4348 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004349 DeclType, CandidateSet,
4350 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004351 }
4352
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004353 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4354
Sebastian Redld92badf2010-06-30 18:13:39 +00004355 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004356 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004357 case OR_Success:
4358 // C++ [over.ics.ref]p1:
4359 //
4360 // [...] If the parameter binds directly to the result of
4361 // applying a conversion function to the argument
4362 // expression, the implicit conversion sequence is a
4363 // user-defined conversion sequence (13.3.3.1.2), with the
4364 // second standard conversion sequence either an identity
4365 // conversion or, if the conversion function returns an
4366 // entity of a type that is a derived class of the parameter
4367 // type, a derived-to-base Conversion.
4368 if (!Best->FinalConversion.DirectBinding)
4369 return false;
4370
4371 ICS.setUserDefined();
4372 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4373 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004374 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004375 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004376 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004377 ICS.UserDefined.EllipsisConversion = false;
4378 assert(ICS.UserDefined.After.ReferenceBinding &&
4379 ICS.UserDefined.After.DirectBinding &&
4380 "Expected a direct reference binding!");
4381 return true;
4382
4383 case OR_Ambiguous:
4384 ICS.setAmbiguous();
4385 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4386 Cand != CandidateSet.end(); ++Cand)
4387 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004388 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004389 return true;
4390
4391 case OR_No_Viable_Function:
4392 case OR_Deleted:
4393 // There was no suitable conversion, or we found a deleted
4394 // conversion; continue with other checks.
4395 return false;
4396 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397
David Blaikie8a40f702012-01-17 06:56:22 +00004398 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004399}
4400
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004401/// \brief Compute an implicit conversion sequence for reference
4402/// initialization.
4403static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004404TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004405 SourceLocation DeclLoc,
4406 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004407 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004408 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4409
4410 // Most paths end in a failed conversion.
4411 ImplicitConversionSequence ICS;
4412 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4413
4414 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4415 QualType T2 = Init->getType();
4416
4417 // If the initializer is the address of an overloaded function, try
4418 // to resolve the overloaded function. If all goes well, T2 is the
4419 // type of the resulting function.
4420 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4421 DeclAccessPair Found;
4422 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4423 false, Found))
4424 T2 = Fn->getType();
4425 }
4426
4427 // Compute some basic properties of the types and the initializer.
4428 bool isRValRef = DeclType->isRValueReferenceType();
4429 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004430 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004431 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004432 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004433 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004434 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004435 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004436
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004437
Sebastian Redld92badf2010-06-30 18:13:39 +00004438 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004439 // A reference to type "cv1 T1" is initialized by an expression
4440 // of type "cv2 T2" as follows:
4441
Sebastian Redld92badf2010-06-30 18:13:39 +00004442 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004443 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004444 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4445 // reference-compatible with "cv2 T2," or
4446 //
4447 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004448 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004449 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004450 // When a parameter of reference type binds directly (8.5.3)
4451 // to an argument expression, the implicit conversion sequence
4452 // is the identity conversion, unless the argument expression
4453 // has a type that is a derived class of the parameter type,
4454 // in which case the implicit conversion sequence is a
4455 // derived-to-base Conversion (13.3.3.1).
4456 ICS.setStandard();
4457 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004458 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4459 : ObjCConversion? ICK_Compatible_Conversion
4460 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004461 ICS.Standard.Third = ICK_Identity;
4462 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4463 ICS.Standard.setToType(0, T2);
4464 ICS.Standard.setToType(1, T1);
4465 ICS.Standard.setToType(2, T1);
4466 ICS.Standard.ReferenceBinding = true;
4467 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004468 ICS.Standard.IsLvalueReference = !isRValRef;
4469 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4470 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004471 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004472 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004473 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004474 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004475
Sebastian Redld92badf2010-06-30 18:13:39 +00004476 // Nothing more to do: the inaccessibility/ambiguity check for
4477 // derived-to-base conversions is suppressed when we're
4478 // computing the implicit conversion sequence (C++
4479 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004480 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004481 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004482
Sebastian Redld92badf2010-06-30 18:13:39 +00004483 // -- has a class type (i.e., T2 is a class type), where T1 is
4484 // not reference-related to T2, and can be implicitly
4485 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4486 // is reference-compatible with "cv3 T3" 92) (this
4487 // conversion is selected by enumerating the applicable
4488 // conversion functions (13.3.1.6) and choosing the best
4489 // one through overload resolution (13.3)),
4490 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004491 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004492 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004493 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4494 Init, T2, /*AllowRvalues=*/false,
4495 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004496 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004497 }
4498 }
4499
Sebastian Redld92badf2010-06-30 18:13:39 +00004500 // -- Otherwise, the reference shall be an lvalue reference to a
4501 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004502 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004503 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004504 return ICS;
4505
Douglas Gregorf143cd52011-01-24 16:14:37 +00004506 // -- If the initializer expression
4507 //
4508 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004509 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004510 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004511 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004512 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4513 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004514 ICS.setStandard();
4515 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004516 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004517 : ObjCConversion? ICK_Compatible_Conversion
4518 : ICK_Identity;
4519 ICS.Standard.Third = ICK_Identity;
4520 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4521 ICS.Standard.setToType(0, T2);
4522 ICS.Standard.setToType(1, T1);
4523 ICS.Standard.setToType(2, T1);
4524 ICS.Standard.ReferenceBinding = true;
4525 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4526 // binding unless we're binding to a class prvalue.
4527 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4528 // allow the use of rvalue references in C++98/03 for the benefit of
4529 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004530 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004531 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004532 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004533 ICS.Standard.IsLvalueReference = !isRValRef;
4534 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004535 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004536 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004537 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004538 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004539 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004540 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004542
Douglas Gregorf143cd52011-01-24 16:14:37 +00004543 // -- has a class type (i.e., T2 is a class type), where T1 is not
4544 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545 // an xvalue, class prvalue, or function lvalue of type
4546 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004547 // "cv3 T3",
4548 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004549 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004550 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004551 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004552 // class subobject).
4553 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004554 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004555 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4556 Init, T2, /*AllowRvalues=*/true,
4557 AllowExplicit)) {
4558 // In the second case, if the reference is an rvalue reference
4559 // and the second standard conversion sequence of the
4560 // user-defined conversion sequence includes an lvalue-to-rvalue
4561 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004562 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004563 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4564 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4565
Douglas Gregor95273c32011-01-21 16:36:05 +00004566 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004567 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568
Richard Smith19172c42014-07-14 02:28:44 +00004569 // A temporary of function type cannot be created; don't even try.
4570 if (T1->isFunctionType())
4571 return ICS;
4572
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004573 // -- Otherwise, a temporary of type "cv1 T1" is created and
4574 // initialized from the initializer expression using the
4575 // rules for a non-reference copy initialization (8.5). The
4576 // reference is then bound to the temporary. If T1 is
4577 // reference-related to T2, cv1 must be the same
4578 // cv-qualification as, or greater cv-qualification than,
4579 // cv2; otherwise, the program is ill-formed.
4580 if (RefRelationship == Sema::Ref_Related) {
4581 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4582 // we would be reference-compatible or reference-compatible with
4583 // added qualification. But that wasn't the case, so the reference
4584 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004585 //
4586 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004587 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004588 Qualifiers T1Quals = T1.getQualifiers();
4589 Qualifiers T2Quals = T2.getQualifiers();
4590 T1Quals.removeObjCGCAttr();
4591 T1Quals.removeObjCLifetime();
4592 T2Quals.removeObjCGCAttr();
4593 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004594 // MS compiler ignores __unaligned qualifier for references; do the same.
4595 T1Quals.removeUnaligned();
4596 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004597 if (!T1Quals.compatiblyIncludes(T2Quals))
4598 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004599 }
4600
4601 // If at least one of the types is a class type, the types are not
4602 // related, and we aren't allowed any user conversions, the
4603 // reference binding fails. This case is important for breaking
4604 // recursion, since TryImplicitConversion below will attempt to
4605 // create a temporary through the use of a copy constructor.
4606 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4607 (T1->isRecordType() || T2->isRecordType()))
4608 return ICS;
4609
Douglas Gregorcba72b12011-01-21 05:18:22 +00004610 // If T1 is reference-related to T2 and the reference is an rvalue
4611 // reference, the initializer expression shall not be an lvalue.
4612 if (RefRelationship >= Sema::Ref_Related &&
4613 isRValRef && Init->Classify(S.Context).isLValue())
4614 return ICS;
4615
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004616 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004617 // When a parameter of reference type is not bound directly to
4618 // an argument expression, the conversion sequence is the one
4619 // required to convert the argument expression to the
4620 // underlying type of the reference according to
4621 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4622 // to copy-initializing a temporary of the underlying type with
4623 // the argument expression. Any difference in top-level
4624 // cv-qualification is subsumed by the initialization itself
4625 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004626 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4627 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004628 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004629 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004630 /*AllowObjCWritebackConversion=*/false,
4631 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004632
4633 // Of course, that's still a reference binding.
4634 if (ICS.isStandard()) {
4635 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004636 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004637 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004638 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004639 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004640 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004641 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004642 const ReferenceType *LValRefType =
4643 ICS.UserDefined.ConversionFunction->getReturnType()
4644 ->getAs<LValueReferenceType>();
4645
4646 // C++ [over.ics.ref]p3:
4647 // Except for an implicit object parameter, for which see 13.3.1, a
4648 // standard conversion sequence cannot be formed if it requires [...]
4649 // binding an rvalue reference to an lvalue other than a function
4650 // lvalue.
4651 // Note that the function case is not possible here.
4652 if (DeclType->isRValueReferenceType() && LValRefType) {
4653 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4654 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4655 // reference to an rvalue!
4656 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4657 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004658 }
Richard Smith19172c42014-07-14 02:28:44 +00004659
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004660 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004661 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004662 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4663 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004664 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4665 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004666 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004667
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004668 return ICS;
4669}
4670
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004671static ImplicitConversionSequence
4672TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4673 bool SuppressUserConversions,
4674 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004675 bool AllowObjCWritebackConversion,
4676 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004677
4678/// TryListConversion - Try to copy-initialize a value of type ToType from the
4679/// initializer list From.
4680static ImplicitConversionSequence
4681TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4682 bool SuppressUserConversions,
4683 bool InOverloadResolution,
4684 bool AllowObjCWritebackConversion) {
4685 // C++11 [over.ics.list]p1:
4686 // When an argument is an initializer list, it is not an expression and
4687 // special rules apply for converting it to a parameter type.
4688
4689 ImplicitConversionSequence Result;
4690 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4691
Sebastian Redl09edce02012-01-23 22:09:39 +00004692 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004693 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004694 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004695 return Result;
4696
Larisse Voufo19d08672015-01-27 18:47:05 +00004697 // Per DR1467:
4698 // If the parameter type is a class X and the initializer list has a single
4699 // element of type cv U, where U is X or a class derived from X, the
4700 // implicit conversion sequence is the one required to convert the element
4701 // to the parameter type.
4702 //
4703 // Otherwise, if the parameter type is a character array [... ]
4704 // and the initializer list has a single element that is an
4705 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4706 // implicit conversion sequence is the identity conversion.
4707 if (From->getNumInits() == 1) {
4708 if (ToType->isRecordType()) {
4709 QualType InitType = From->getInit(0)->getType();
4710 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004711 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004712 return TryCopyInitialization(S, From->getInit(0), ToType,
4713 SuppressUserConversions,
4714 InOverloadResolution,
4715 AllowObjCWritebackConversion);
4716 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004717 // FIXME: Check the other conditions here: array of character type,
4718 // initializer is a string literal.
4719 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004720 InitializedEntity Entity =
4721 InitializedEntity::InitializeParameter(S.Context, ToType,
4722 /*Consumed=*/false);
4723 if (S.CanPerformCopyInitialization(Entity, From)) {
4724 Result.setStandard();
4725 Result.Standard.setAsIdentityConversion();
4726 Result.Standard.setFromType(ToType);
4727 Result.Standard.setAllToTypes(ToType);
4728 return Result;
4729 }
4730 }
4731 }
4732
4733 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004734 // C++11 [over.ics.list]p2:
4735 // If the parameter type is std::initializer_list<X> or "array of X" and
4736 // all the elements can be implicitly converted to X, the implicit
4737 // conversion sequence is the worst conversion necessary to convert an
4738 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004739 //
4740 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004741 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004742 // list has exactly N elements or if it has fewer than N elements and X is
4743 // default-constructible, and if all the elements of the initializer list
4744 // can be implicitly converted to X, the implicit conversion sequence is
4745 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004746 //
4747 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004748 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004749 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004750 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004751 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004752 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004753 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004754 if (!X.isNull()) {
4755 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4756 Expr *Init = From->getInit(i);
4757 ImplicitConversionSequence ICS =
4758 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4759 InOverloadResolution,
4760 AllowObjCWritebackConversion);
4761 // If a single element isn't convertible, fail.
4762 if (ICS.isBad()) {
4763 Result = ICS;
4764 break;
4765 }
4766 // Otherwise, look for the worst conversion.
4767 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004768 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4769 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004770 ImplicitConversionSequence::Worse)
4771 Result = ICS;
4772 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004773
4774 // For an empty list, we won't have computed any conversion sequence.
4775 // Introduce the identity conversion sequence.
4776 if (From->getNumInits() == 0) {
4777 Result.setStandard();
4778 Result.Standard.setAsIdentityConversion();
4779 Result.Standard.setFromType(ToType);
4780 Result.Standard.setAllToTypes(ToType);
4781 }
4782
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004783 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004784 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004785 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004786
Larisse Voufo19d08672015-01-27 18:47:05 +00004787 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004788 // C++11 [over.ics.list]p3:
4789 // Otherwise, if the parameter is a non-aggregate class X and overload
4790 // resolution chooses a single best constructor [...] the implicit
4791 // conversion sequence is a user-defined conversion sequence. If multiple
4792 // constructors are viable but none is better than the others, the
4793 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004794 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4795 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004796 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4797 /*AllowExplicit=*/false,
4798 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004799 AllowObjCWritebackConversion,
4800 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004801 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004802
Larisse Voufo19d08672015-01-27 18:47:05 +00004803 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004804 // C++11 [over.ics.list]p4:
4805 // Otherwise, if the parameter has an aggregate type which can be
4806 // initialized from the initializer list [...] the implicit conversion
4807 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004808 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004809 // Type is an aggregate, argument is an init list. At this point it comes
4810 // down to checking whether the initialization works.
4811 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004812 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4813 // need to call into the initialization code here; overload resolution
4814 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004815 InitializedEntity Entity =
4816 InitializedEntity::InitializeParameter(S.Context, ToType,
4817 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004818 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004819 Result.setUserDefined();
4820 Result.UserDefined.Before.setAsIdentityConversion();
4821 // Initializer lists don't have a type.
4822 Result.UserDefined.Before.setFromType(QualType());
4823 Result.UserDefined.Before.setAllToTypes(QualType());
4824
4825 Result.UserDefined.After.setAsIdentityConversion();
4826 Result.UserDefined.After.setFromType(ToType);
4827 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004828 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004829 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004830 return Result;
4831 }
4832
Larisse Voufo19d08672015-01-27 18:47:05 +00004833 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004834 // C++11 [over.ics.list]p5:
4835 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004836 if (ToType->isReferenceType()) {
4837 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4838 // mention initializer lists in any way. So we go by what list-
4839 // initialization would do and try to extrapolate from that.
4840
4841 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4842
4843 // If the initializer list has a single element that is reference-related
4844 // to the parameter type, we initialize the reference from that.
4845 if (From->getNumInits() == 1) {
4846 Expr *Init = From->getInit(0);
4847
4848 QualType T2 = Init->getType();
4849
4850 // If the initializer is the address of an overloaded function, try
4851 // to resolve the overloaded function. If all goes well, T2 is the
4852 // type of the resulting function.
4853 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4854 DeclAccessPair Found;
4855 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4856 Init, ToType, false, Found))
4857 T2 = Fn->getType();
4858 }
4859
4860 // Compute some basic properties of the types and the initializer.
4861 bool dummy1 = false;
4862 bool dummy2 = false;
4863 bool dummy3 = false;
4864 Sema::ReferenceCompareResult RefRelationship
4865 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4866 dummy2, dummy3);
4867
Richard Smith4d2bbd72013-09-06 01:22:42 +00004868 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004869 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4870 SuppressUserConversions,
4871 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004872 }
Sebastian Redldf888642011-12-03 14:54:30 +00004873 }
4874
4875 // Otherwise, we bind the reference to a temporary created from the
4876 // initializer list.
4877 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4878 InOverloadResolution,
4879 AllowObjCWritebackConversion);
4880 if (Result.isFailure())
4881 return Result;
4882 assert(!Result.isEllipsis() &&
4883 "Sub-initialization cannot result in ellipsis conversion.");
4884
4885 // Can we even bind to a temporary?
4886 if (ToType->isRValueReferenceType() ||
4887 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4888 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4889 Result.UserDefined.After;
4890 SCS.ReferenceBinding = true;
4891 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4892 SCS.BindsToRvalue = true;
4893 SCS.BindsToFunctionLvalue = false;
4894 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4895 SCS.ObjCLifetimeConversionBinding = false;
4896 } else
4897 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4898 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004899 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004900 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004901
Larisse Voufo19d08672015-01-27 18:47:05 +00004902 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004903 // C++11 [over.ics.list]p6:
4904 // Otherwise, if the parameter type is not a class:
4905 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004906 // - if the initializer list has one element that is not itself an
4907 // initializer list, the implicit conversion sequence is the one
4908 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004909 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004910 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004911 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4912 SuppressUserConversions,
4913 InOverloadResolution,
4914 AllowObjCWritebackConversion);
4915 // - if the initializer list has no elements, the implicit conversion
4916 // sequence is the identity conversion.
4917 else if (NumInits == 0) {
4918 Result.setStandard();
4919 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004920 Result.Standard.setFromType(ToType);
4921 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004922 }
4923 return Result;
4924 }
4925
Larisse Voufo19d08672015-01-27 18:47:05 +00004926 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004927 // C++11 [over.ics.list]p7:
4928 // In all cases other than those enumerated above, no conversion is possible
4929 return Result;
4930}
4931
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004932/// TryCopyInitialization - Try to copy-initialize a value of type
4933/// ToType from the expression From. Return the implicit conversion
4934/// sequence required to pass this argument, which may be a bad
4935/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004936/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004937/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004938static ImplicitConversionSequence
4939TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004941 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004942 bool AllowObjCWritebackConversion,
4943 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004944 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4945 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4946 InOverloadResolution,AllowObjCWritebackConversion);
4947
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004948 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004949 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004950 /*FIXME:*/From->getLocStart(),
4951 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004952 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004953
John McCall5c32be02010-08-24 20:38:10 +00004954 return TryImplicitConversion(S, From, ToType,
4955 SuppressUserConversions,
4956 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004957 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004958 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004959 AllowObjCWritebackConversion,
4960 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004961}
4962
Anna Zaks1b068122011-07-28 19:46:48 +00004963static bool TryCopyInitialization(const CanQualType FromQTy,
4964 const CanQualType ToQTy,
4965 Sema &S,
4966 SourceLocation Loc,
4967 ExprValueKind FromVK) {
4968 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4969 ImplicitConversionSequence ICS =
4970 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4971
4972 return !ICS.isBad();
4973}
4974
Douglas Gregor436424c2008-11-18 23:14:02 +00004975/// TryObjectArgumentInitialization - Try to initialize the object
4976/// parameter of the given member function (@c Method) from the
4977/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004978static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004979TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004980 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004981 CXXMethodDecl *Method,
4982 CXXRecordDecl *ActingContext) {
4983 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004984 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4985 // const volatile object.
4986 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4987 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004988 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004989
4990 // Set up the conversion sequence as a "bad" conversion, to allow us
4991 // to exit early.
4992 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004993
4994 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004995 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004996 FromType = PT->getPointeeType();
4997
Douglas Gregor02824322011-01-26 19:30:28 +00004998 // When we had a pointer, it's implicitly dereferenced, so we
4999 // better have an lvalue.
5000 assert(FromClassification.isLValue());
5001 }
5002
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005003 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00005004
Douglas Gregor02824322011-01-26 19:30:28 +00005005 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005006 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00005007 // parameter is
5008 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005009 // - "lvalue reference to cv X" for functions declared without a
5010 // ref-qualifier or with the & ref-qualifier
5011 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00005012 // ref-qualifier
5013 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005014 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00005015 // cv-qualification on the member function declaration.
5016 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005017 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005018 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005019 // (C++ [over.match.funcs]p5). We perform a simplified version of
5020 // reference binding here, that allows class rvalues to bind to
5021 // non-constant references.
5022
Douglas Gregor02824322011-01-26 19:30:28 +00005023 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005024 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005025 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005026 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005027 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005028 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005029 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005030 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005031 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005032
5033 // Check that we have either the same type or a derived type. It
5034 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005035 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005036 ImplicitConversionKind SecondKind;
5037 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5038 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005039 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005040 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005041 else {
John McCall65eb8792010-02-25 01:37:24 +00005042 ICS.setBad(BadConversionSequence::unrelated_class,
5043 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005044 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005045 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005046
Douglas Gregor02824322011-01-26 19:30:28 +00005047 // Check the ref-qualifier.
5048 switch (Method->getRefQualifier()) {
5049 case RQ_None:
5050 // Do nothing; we don't care about lvalueness or rvalueness.
5051 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005052
Douglas Gregor02824322011-01-26 19:30:28 +00005053 case RQ_LValue:
5054 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5055 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005056 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005057 ImplicitParamType);
5058 return ICS;
5059 }
5060 break;
5061
5062 case RQ_RValue:
5063 if (!FromClassification.isRValue()) {
5064 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005065 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005066 ImplicitParamType);
5067 return ICS;
5068 }
5069 break;
5070 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005071
Douglas Gregor436424c2008-11-18 23:14:02 +00005072 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005073 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005074 ICS.Standard.setAsIdentityConversion();
5075 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005076 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005077 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005078 ICS.Standard.ReferenceBinding = true;
5079 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005080 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005081 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005082 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5083 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5084 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005085 return ICS;
5086}
5087
5088/// PerformObjectArgumentInitialization - Perform initialization of
5089/// the implicit object parameter for the given Method with the given
5090/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005091ExprResult
5092Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005093 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005094 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005095 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005096 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005097 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005098 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005099
Douglas Gregor02824322011-01-26 19:30:28 +00005100 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005101 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005102 FromRecordType = PT->getPointeeType();
5103 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005104 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005105 } else {
5106 FromRecordType = From->getType();
5107 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005108 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005109 }
5110
John McCall6e9f8f62009-12-03 04:06:58 +00005111 // Note that we always use the true parent context when performing
5112 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005113 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005114 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5115 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005116 if (ICS.isBad()) {
5117 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5118 Qualifiers FromQs = FromRecordType.getQualifiers();
5119 Qualifiers ToQs = DestType.getQualifiers();
5120 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5121 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005122 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005123 diag::err_member_function_call_bad_cvr)
5124 << Method->getDeclName() << FromRecordType << (CVR - 1)
5125 << From->getSourceRange();
5126 Diag(Method->getLocation(), diag::note_previous_decl)
5127 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005128 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005129 }
5130 }
5131
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005132 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005133 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005134 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005135 }
Mike Stump11289f42009-09-09 15:08:12 +00005136
John Wiegley01296292011-04-08 18:41:53 +00005137 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5138 ExprResult FromRes =
5139 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5140 if (FromRes.isInvalid())
5141 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005142 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005143 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005144
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005145 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005146 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005147 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005148 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005149}
5150
Douglas Gregor5fb53972009-01-14 15:45:31 +00005151/// TryContextuallyConvertToBool - Attempt to contextually convert the
5152/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005153static ImplicitConversionSequence
5154TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005155 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005156 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005157 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005158 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005159 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005160 /*AllowObjCWritebackConversion=*/false,
5161 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005162}
5163
5164/// PerformContextuallyConvertToBool - Perform a contextual conversion
5165/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005166ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005167 if (checkPlaceholderForOverload(*this, From))
5168 return ExprError();
5169
John McCall5c32be02010-08-24 20:38:10 +00005170 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005171 if (!ICS.isBad())
5172 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005173
Fariborz Jahanian76197412009-11-18 18:26:29 +00005174 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005175 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005176 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005177 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005178 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005179}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005180
Richard Smithf8379a02012-01-18 23:55:52 +00005181/// Check that the specified conversion is permitted in a converted constant
5182/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5183/// is acceptable.
5184static bool CheckConvertedConstantConversions(Sema &S,
5185 StandardConversionSequence &SCS) {
5186 // Since we know that the target type is an integral or unscoped enumeration
5187 // type, most conversion kinds are impossible. All possible First and Third
5188 // conversions are fine.
5189 switch (SCS.Second) {
5190 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005191 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005192 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005193 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Egor Churaev89831422016-12-23 14:55:49 +00005194 case ICK_Zero_Queue_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005195 return true;
5196
5197 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005198 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005199 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5200 // conversion, so we allow it in a converted constant expression.
5201 //
5202 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5203 // a lot of popular code. We should at least add a warning for this
5204 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005205 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5206 SCS.getToType(2)->isBooleanType();
5207
Richard Smith410cc892014-11-26 03:26:53 +00005208 case ICK_Pointer_Conversion:
5209 case ICK_Pointer_Member:
5210 // C++1z: null pointer conversions and null member pointer conversions are
5211 // only permitted if the source type is std::nullptr_t.
5212 return SCS.getFromType()->isNullPtrType();
5213
5214 case ICK_Floating_Promotion:
5215 case ICK_Complex_Promotion:
5216 case ICK_Floating_Conversion:
5217 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005218 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005219 case ICK_Compatible_Conversion:
5220 case ICK_Derived_To_Base:
5221 case ICK_Vector_Conversion:
5222 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005223 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005224 case ICK_Block_Pointer_Conversion:
5225 case ICK_TransparentUnionConversion:
5226 case ICK_Writeback_Conversion:
5227 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005228 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005229 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005230 return false;
5231
5232 case ICK_Lvalue_To_Rvalue:
5233 case ICK_Array_To_Pointer:
5234 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005235 llvm_unreachable("found a first conversion kind in Second");
5236
Richard Smithf8379a02012-01-18 23:55:52 +00005237 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005238 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005239
5240 case ICK_Num_Conversion_Kinds:
5241 break;
5242 }
5243
5244 llvm_unreachable("unknown conversion kind");
5245}
5246
5247/// CheckConvertedConstantExpression - Check that the expression From is a
5248/// converted constant expression of type T, perform the conversion and produce
5249/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005250static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5251 QualType T, APValue &Value,
5252 Sema::CCEKind CCE,
5253 bool RequireInt) {
5254 assert(S.getLangOpts().CPlusPlus11 &&
5255 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005256
Richard Smith410cc892014-11-26 03:26:53 +00005257 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005258 return ExprError();
5259
Richard Smith410cc892014-11-26 03:26:53 +00005260 // C++1z [expr.const]p3:
5261 // A converted constant expression of type T is an expression,
5262 // implicitly converted to type T, where the converted
5263 // expression is a constant expression and the implicit conversion
5264 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005265 // C++1z [stmt.if]p2:
5266 // If the if statement is of the form if constexpr, the value of the
5267 // condition shall be a contextually converted constant expression of type
5268 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005269 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005270 CCE == Sema::CCEK_ConstexprIf
5271 ? TryContextuallyConvertToBool(S, From)
5272 : TryCopyInitialization(S, From, T,
5273 /*SuppressUserConversions=*/false,
5274 /*InOverloadResolution=*/false,
5275 /*AllowObjcWritebackConversion=*/false,
5276 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005277 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005278 switch (ICS.getKind()) {
5279 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005280 SCS = &ICS.Standard;
5281 break;
5282 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005283 // We are converting to a non-class type, so the Before sequence
5284 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005285 SCS = &ICS.UserDefined.After;
5286 break;
5287 case ImplicitConversionSequence::AmbiguousConversion:
5288 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005289 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5290 return S.Diag(From->getLocStart(),
5291 diag::err_typecheck_converted_constant_expression)
5292 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005293 return ExprError();
5294
5295 case ImplicitConversionSequence::EllipsisConversion:
5296 llvm_unreachable("ellipsis conversion in converted constant expression");
5297 }
5298
Richard Smith410cc892014-11-26 03:26:53 +00005299 // Check that we would only use permitted conversions.
5300 if (!CheckConvertedConstantConversions(S, *SCS)) {
5301 return S.Diag(From->getLocStart(),
5302 diag::err_typecheck_converted_constant_expression_disallowed)
5303 << From->getType() << From->getSourceRange() << T;
5304 }
5305 // [...] and where the reference binding (if any) binds directly.
5306 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5307 return S.Diag(From->getLocStart(),
5308 diag::err_typecheck_converted_constant_expression_indirect)
5309 << From->getType() << From->getSourceRange() << T;
5310 }
5311
5312 ExprResult Result =
5313 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005314 if (Result.isInvalid())
5315 return Result;
5316
5317 // Check for a narrowing implicit conversion.
5318 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005319 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005320 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005321 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005322 case NK_Dependent_Narrowing:
5323 // Implicit conversion to a narrower type, but the expression is
5324 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005325 case NK_Variable_Narrowing:
5326 // Implicit conversion to a narrower type, and the value is not a constant
5327 // expression. We'll diagnose this in a moment.
5328 case NK_Not_Narrowing:
5329 break;
5330
5331 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005332 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005333 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005334 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005335 break;
5336
5337 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005338 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005339 << CCE << /*Constant*/0 << From->getType() << T;
5340 break;
5341 }
5342
Richard Smith52e624f2016-12-21 21:42:57 +00005343 if (Result.get()->isValueDependent()) {
5344 Value = APValue();
5345 return Result;
5346 }
5347
Richard Smithf8379a02012-01-18 23:55:52 +00005348 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005349 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005350 Expr::EvalResult Eval;
5351 Eval.Diag = &Notes;
5352
Richard Smith410cc892014-11-26 03:26:53 +00005353 if ((T->isReferenceType()
5354 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5355 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5356 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005357 // The expression can't be folded, so we can't keep it at this position in
5358 // the AST.
5359 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005360 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005361 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005362
5363 if (Notes.empty()) {
5364 // It's a constant expression.
5365 return Result;
5366 }
Richard Smithf8379a02012-01-18 23:55:52 +00005367 }
5368
5369 // It's not a constant expression. Produce an appropriate diagnostic.
5370 if (Notes.size() == 1 &&
5371 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005372 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005373 else {
Richard Smith410cc892014-11-26 03:26:53 +00005374 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005375 << CCE << From->getSourceRange();
5376 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005377 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005378 }
Richard Smith410cc892014-11-26 03:26:53 +00005379 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005380}
5381
Richard Smith410cc892014-11-26 03:26:53 +00005382ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5383 APValue &Value, CCEKind CCE) {
5384 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5385}
5386
5387ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5388 llvm::APSInt &Value,
5389 CCEKind CCE) {
5390 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5391
5392 APValue V;
5393 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
Richard Smith01bfa682016-12-27 02:02:09 +00005394 if (!R.isInvalid() && !R.get()->isValueDependent())
Richard Smith410cc892014-11-26 03:26:53 +00005395 Value = V.getInt();
5396 return R;
5397}
5398
5399
John McCallfec112d2011-09-09 06:11:02 +00005400/// dropPointerConversions - If the given standard conversion sequence
5401/// involves any pointer conversions, remove them. This may change
5402/// the result type of the conversion sequence.
5403static void dropPointerConversion(StandardConversionSequence &SCS) {
5404 if (SCS.Second == ICK_Pointer_Conversion) {
5405 SCS.Second = ICK_Identity;
5406 SCS.Third = ICK_Identity;
5407 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5408 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005409}
John McCall5c32be02010-08-24 20:38:10 +00005410
John McCallfec112d2011-09-09 06:11:02 +00005411/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5412/// convert the expression From to an Objective-C pointer type.
5413static ImplicitConversionSequence
5414TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5415 // Do an implicit conversion to 'id'.
5416 QualType Ty = S.Context.getObjCIdType();
5417 ImplicitConversionSequence ICS
5418 = TryImplicitConversion(S, From, Ty,
5419 // FIXME: Are these flags correct?
5420 /*SuppressUserConversions=*/false,
5421 /*AllowExplicit=*/true,
5422 /*InOverloadResolution=*/false,
5423 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005424 /*AllowObjCWritebackConversion=*/false,
5425 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005426
5427 // Strip off any final conversions to 'id'.
5428 switch (ICS.getKind()) {
5429 case ImplicitConversionSequence::BadConversion:
5430 case ImplicitConversionSequence::AmbiguousConversion:
5431 case ImplicitConversionSequence::EllipsisConversion:
5432 break;
5433
5434 case ImplicitConversionSequence::UserDefinedConversion:
5435 dropPointerConversion(ICS.UserDefined.After);
5436 break;
5437
5438 case ImplicitConversionSequence::StandardConversion:
5439 dropPointerConversion(ICS.Standard);
5440 break;
5441 }
5442
5443 return ICS;
5444}
5445
5446/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5447/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005448/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005449ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005450 if (checkPlaceholderForOverload(*this, From))
5451 return ExprError();
5452
John McCall8b07ec22010-05-15 11:32:37 +00005453 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005454 ImplicitConversionSequence ICS =
5455 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005456 if (!ICS.isBad())
5457 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005458 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005459}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005460
Richard Smith8dd34252012-02-04 07:07:42 +00005461/// Determine whether the provided type is an integral type, or an enumeration
5462/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005463bool Sema::ICEConvertDiagnoser::match(QualType T) {
5464 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5465 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005466}
5467
Larisse Voufo236bec22013-06-10 06:50:24 +00005468static ExprResult
5469diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5470 Sema::ContextualImplicitConverter &Converter,
5471 QualType T, UnresolvedSetImpl &ViableConversions) {
5472
5473 if (Converter.Suppress)
5474 return ExprError();
5475
5476 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5477 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5478 CXXConversionDecl *Conv =
5479 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5480 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5481 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5482 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005483 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005484}
5485
5486static bool
5487diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5488 Sema::ContextualImplicitConverter &Converter,
5489 QualType T, bool HadMultipleCandidates,
5490 UnresolvedSetImpl &ExplicitConversions) {
5491 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5492 DeclAccessPair Found = ExplicitConversions[0];
5493 CXXConversionDecl *Conversion =
5494 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5495
5496 // The user probably meant to invoke the given explicit
5497 // conversion; use it.
5498 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5499 std::string TypeStr;
5500 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5501
5502 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5503 << FixItHint::CreateInsertion(From->getLocStart(),
5504 "static_cast<" + TypeStr + ">(")
5505 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005506 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005507 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5508
5509 // If we aren't in a SFINAE context, build a call to the
5510 // explicit conversion function.
5511 if (SemaRef.isSFINAEContext())
5512 return true;
5513
Craig Topperc3ec1492014-05-26 06:22:03 +00005514 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005515 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5516 HadMultipleCandidates);
5517 if (Result.isInvalid())
5518 return true;
5519 // Record usage of conversion in an implicit cast.
5520 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005521 CK_UserDefinedConversion, Result.get(),
5522 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005523 }
5524 return false;
5525}
5526
5527static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5528 Sema::ContextualImplicitConverter &Converter,
5529 QualType T, bool HadMultipleCandidates,
5530 DeclAccessPair &Found) {
5531 CXXConversionDecl *Conversion =
5532 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005533 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005534
5535 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5536 if (!Converter.SuppressConversion) {
5537 if (SemaRef.isSFINAEContext())
5538 return true;
5539
5540 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5541 << From->getSourceRange();
5542 }
5543
5544 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5545 HadMultipleCandidates);
5546 if (Result.isInvalid())
5547 return true;
5548 // Record usage of conversion in an implicit cast.
5549 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005550 CK_UserDefinedConversion, Result.get(),
5551 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005552 return false;
5553}
5554
5555static ExprResult finishContextualImplicitConversion(
5556 Sema &SemaRef, SourceLocation Loc, Expr *From,
5557 Sema::ContextualImplicitConverter &Converter) {
5558 if (!Converter.match(From->getType()) && !Converter.Suppress)
5559 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5560 << From->getSourceRange();
5561
5562 return SemaRef.DefaultLvalueConversion(From);
5563}
5564
5565static void
5566collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5567 UnresolvedSetImpl &ViableConversions,
5568 OverloadCandidateSet &CandidateSet) {
5569 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5570 DeclAccessPair FoundDecl = ViableConversions[I];
5571 NamedDecl *D = FoundDecl.getDecl();
5572 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5573 if (isa<UsingShadowDecl>(D))
5574 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5575
5576 CXXConversionDecl *Conv;
5577 FunctionTemplateDecl *ConvTemplate;
5578 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5579 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5580 else
5581 Conv = cast<CXXConversionDecl>(D);
5582
5583 if (ConvTemplate)
5584 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005585 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5586 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005587 else
5588 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005589 ToType, CandidateSet,
5590 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005591 }
5592}
5593
Richard Smithccc11812013-05-21 19:05:48 +00005594/// \brief Attempt to convert the given expression to a type which is accepted
5595/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005596///
Richard Smithccc11812013-05-21 19:05:48 +00005597/// This routine will attempt to convert an expression of class type to a
5598/// type accepted by the specified converter. In C++11 and before, the class
5599/// must have a single non-explicit conversion function converting to a matching
5600/// type. In C++1y, there can be multiple such conversion functions, but only
5601/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005602///
Douglas Gregor4799d032010-06-30 00:20:43 +00005603/// \param Loc The source location of the construct that requires the
5604/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005605///
James Dennett18348b62012-06-22 08:52:37 +00005606/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005607///
Richard Smithccc11812013-05-21 19:05:48 +00005608/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005609///
Douglas Gregor4799d032010-06-30 00:20:43 +00005610/// \returns The expression, converted to an integral or enumeration type if
5611/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005612ExprResult Sema::PerformContextualImplicitConversion(
5613 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005614 // We can't perform any more checking for type-dependent expressions.
5615 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005616 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005617
Eli Friedman1da70392012-01-26 00:26:18 +00005618 // Process placeholders immediately.
5619 if (From->hasPlaceholderType()) {
5620 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005621 if (result.isInvalid())
5622 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005623 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005624 }
5625
Richard Smithccc11812013-05-21 19:05:48 +00005626 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005627 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005628 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005629 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005630
5631 // FIXME: Check for missing '()' if T is a function type?
5632
Richard Smithccc11812013-05-21 19:05:48 +00005633 // We can only perform contextual implicit conversions on objects of class
5634 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005635 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005636 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005637 if (!Converter.Suppress)
5638 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005639 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005640 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005641
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005642 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005643 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005644 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005645 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005646
5647 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005648 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005649
Craig Toppere14c0f82014-03-12 04:55:44 +00005650 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005651 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005652 }
Richard Smithccc11812013-05-21 19:05:48 +00005653 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005654
Richard Smithdb0ac552015-12-18 22:40:25 +00005655 if (Converter.Suppress ? !isCompleteType(Loc, T)
5656 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005657 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005658
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005659 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005660 UnresolvedSet<4>
5661 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005662 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005663 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005664 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005665
Larisse Voufo236bec22013-06-10 06:50:24 +00005666 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005667 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005668
Larisse Voufo236bec22013-06-10 06:50:24 +00005669 // To check that there is only one target type, in C++1y:
5670 QualType ToType;
5671 bool HasUniqueTargetType = true;
5672
5673 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005674 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005675 NamedDecl *D = (*I)->getUnderlyingDecl();
5676 CXXConversionDecl *Conversion;
5677 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5678 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005679 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005680 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5681 else
5682 continue; // C++11 does not consider conversion operator templates(?).
5683 } else
5684 Conversion = cast<CXXConversionDecl>(D);
5685
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005686 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005687 "Conversion operator templates are considered potentially "
5688 "viable in C++1y");
5689
5690 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5691 if (Converter.match(CurToType) || ConvTemplate) {
5692
5693 if (Conversion->isExplicit()) {
5694 // FIXME: For C++1y, do we need this restriction?
5695 // cf. diagnoseNoViableConversion()
5696 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005697 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005698 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005699 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005700 if (ToType.isNull())
5701 ToType = CurToType.getUnqualifiedType();
5702 else if (HasUniqueTargetType &&
5703 (CurToType.getUnqualifiedType() != ToType))
5704 HasUniqueTargetType = false;
5705 }
5706 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005707 }
Richard Smith8dd34252012-02-04 07:07:42 +00005708 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005709 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005710
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005711 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005712 // C++1y [conv]p6:
5713 // ... An expression e of class type E appearing in such a context
5714 // is said to be contextually implicitly converted to a specified
5715 // type T and is well-formed if and only if e can be implicitly
5716 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005717 // for conversion functions whose return type is cv T or reference to
5718 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005719 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720
Larisse Voufo236bec22013-06-10 06:50:24 +00005721 // If no unique T is found:
5722 if (ToType.isNull()) {
5723 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5724 HadMultipleCandidates,
5725 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005726 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005727 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005728 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005729
Larisse Voufo236bec22013-06-10 06:50:24 +00005730 // If more than one unique Ts are found:
5731 if (!HasUniqueTargetType)
5732 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5733 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005734
Larisse Voufo236bec22013-06-10 06:50:24 +00005735 // If one unique T is found:
5736 // First, build a candidate set from the previously recorded
5737 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005738 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005739 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5740 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741
Larisse Voufo236bec22013-06-10 06:50:24 +00005742 // Then, perform overload resolution over the candidate set.
5743 OverloadCandidateSet::iterator Best;
5744 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5745 case OR_Success: {
5746 // Apply this conversion.
5747 DeclAccessPair Found =
5748 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5749 if (recordConversion(*this, Loc, From, Converter, T,
5750 HadMultipleCandidates, Found))
5751 return ExprError();
5752 break;
5753 }
5754 case OR_Ambiguous:
5755 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5756 ViableConversions);
5757 case OR_No_Viable_Function:
5758 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5759 HadMultipleCandidates,
5760 ExplicitConversions))
5761 return ExprError();
5762 // fall through 'OR_Deleted' case.
5763 case OR_Deleted:
5764 // We'll complain below about a non-integral condition type.
5765 break;
5766 }
5767 } else {
5768 switch (ViableConversions.size()) {
5769 case 0: {
5770 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5771 HadMultipleCandidates,
5772 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005773 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005774
Larisse Voufo236bec22013-06-10 06:50:24 +00005775 // We'll complain below about a non-integral condition type.
5776 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005777 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005778 case 1: {
5779 // Apply this conversion.
5780 DeclAccessPair Found = ViableConversions[0];
5781 if (recordConversion(*this, Loc, From, Converter, T,
5782 HadMultipleCandidates, Found))
5783 return ExprError();
5784 break;
5785 }
5786 default:
5787 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5788 ViableConversions);
5789 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005790 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005791
Larisse Voufo236bec22013-06-10 06:50:24 +00005792 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005793}
5794
Richard Smith100b24a2014-04-17 01:52:14 +00005795/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5796/// an acceptable non-member overloaded operator for a call whose
5797/// arguments have types T1 (and, if non-empty, T2). This routine
5798/// implements the check in C++ [over.match.oper]p3b2 concerning
5799/// enumeration types.
5800static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5801 FunctionDecl *Fn,
5802 ArrayRef<Expr *> Args) {
5803 QualType T1 = Args[0]->getType();
5804 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5805
5806 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5807 return true;
5808
5809 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5810 return true;
5811
5812 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5813 if (Proto->getNumParams() < 1)
5814 return false;
5815
5816 if (T1->isEnumeralType()) {
5817 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5818 if (Context.hasSameUnqualifiedType(T1, ArgType))
5819 return true;
5820 }
5821
5822 if (Proto->getNumParams() < 2)
5823 return false;
5824
5825 if (!T2.isNull() && T2->isEnumeralType()) {
5826 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5827 if (Context.hasSameUnqualifiedType(T2, ArgType))
5828 return true;
5829 }
5830
5831 return false;
5832}
5833
George Burgess IV177399e2017-01-09 04:12:14 +00005834static void initDiagnoseIfComplaint(Sema &S, OverloadCandidateSet &CandidateSet,
5835 OverloadCandidate &Candidate,
5836 FunctionDecl *Function,
5837 ArrayRef<Expr *> Args,
5838 bool MissingImplicitThis = false,
5839 Expr *ExplicitThis = nullptr) {
5840 SmallVector<DiagnoseIfAttr *, 8> Results;
5841 if (DiagnoseIfAttr *DIA = S.checkArgDependentDiagnoseIf(
5842 Function, Args, Results, MissingImplicitThis, ExplicitThis)) {
5843 Results.clear();
5844 Results.push_back(DIA);
5845 }
5846
5847 Candidate.NumTriggeredDiagnoseIfs = Results.size();
5848 if (Results.empty())
5849 Candidate.DiagnoseIfInfo = nullptr;
5850 else if (Results.size() == 1)
5851 Candidate.DiagnoseIfInfo = Results[0];
5852 else
5853 Candidate.DiagnoseIfInfo = CandidateSet.addDiagnoseIfComplaints(Results);
5854}
5855
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005856/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005857/// candidate functions, using the given function call arguments. If
5858/// @p SuppressUserConversions, then don't allow user-defined
5859/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005860///
James Dennett2a4d13c2012-06-15 07:13:21 +00005861/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005862/// based on an incomplete set of function arguments. This feature is used by
5863/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005864void
5865Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005866 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005867 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005868 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005869 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005870 bool PartialOverloading,
Richard Smith6eedfe72017-01-09 08:01:21 +00005871 bool AllowExplicit,
5872 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005873 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005874 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005875 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005876 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005877 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005878
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005879 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005880 if (!isa<CXXConstructorDecl>(Method)) {
5881 // If we get here, it's because we're calling a member function
5882 // that is named without a member access expression (e.g.,
5883 // "this->f") that was either written explicitly or created
5884 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005885 // function, e.g., X::f(). We use an empty type for the implied
5886 // object argument (C++ [over.call.func]p3), and the acting context
5887 // is irrelevant.
Richard Smith6eedfe72017-01-09 08:01:21 +00005888 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5889 Expr::Classification::makeSimpleLValue(),
George Burgess IV177399e2017-01-09 04:12:14 +00005890 /*ThisArg=*/nullptr, Args, CandidateSet,
Richard Smith6eedfe72017-01-09 08:01:21 +00005891 SuppressUserConversions, PartialOverloading,
5892 EarlyConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005893 return;
5894 }
5895 // We treat a constructor like a non-member function, since its object
5896 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005897 }
5898
Douglas Gregorff7028a2009-11-13 23:59:09 +00005899 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005900 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005901
Richard Smith100b24a2014-04-17 01:52:14 +00005902 // C++ [over.match.oper]p3:
5903 // if no operand has a class type, only those non-member functions in the
5904 // lookup set that have a first parameter of type T1 or "reference to
5905 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5906 // is a right operand) a second parameter of type T2 or "reference to
5907 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5908 // candidate functions.
5909 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5910 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5911 return;
5912
Richard Smith8b86f2d2013-11-04 01:48:18 +00005913 // C++11 [class.copy]p11: [DR1402]
5914 // A defaulted move constructor that is defined as deleted is ignored by
5915 // overload resolution.
5916 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5917 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5918 Constructor->isMoveConstructor())
5919 return;
5920
Douglas Gregor27381f32009-11-23 12:27:39 +00005921 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005922 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005923
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005924 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00005925 OverloadCandidate &Candidate =
5926 CandidateSet.addCandidate(Args.size(), EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00005927 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005928 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005929 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005930 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005931 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005932 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005933
John McCall578a1f82014-12-14 01:46:53 +00005934 if (Constructor) {
5935 // C++ [class.copy]p3:
5936 // A member function template is never instantiated to perform the copy
5937 // of a class object to an object of its class type.
5938 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005939 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005940 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005941 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5942 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005943 Candidate.Viable = false;
5944 Candidate.FailureKind = ovl_fail_illegal_constructor;
5945 return;
5946 }
5947 }
5948
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005949 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005950
5951 // (C++ 13.3.2p2): A candidate function having fewer than m
5952 // parameters is viable only if it has an ellipsis in its parameter
5953 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005954 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005955 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005956 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005957 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005958 return;
5959 }
5960
5961 // (C++ 13.3.2p2): A candidate function having more than m parameters
5962 // is viable only if the (m+1)st parameter has a default argument
5963 // (8.3.6). For the purposes of overload resolution, the
5964 // parameter list is truncated on the right, so that there are
5965 // exactly m parameters.
5966 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005967 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005968 // Not enough arguments.
5969 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005970 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005971 return;
5972 }
5973
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005974 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005975 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005976 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005977 // Skip the check for callers that are implicit members, because in this
5978 // case we may not yet know what the member's target is; the target is
5979 // inferred for the member automatically, based on the bases and fields of
5980 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00005981 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005982 Candidate.Viable = false;
5983 Candidate.FailureKind = ovl_fail_bad_target;
5984 return;
5985 }
5986
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005987 // Determine the implicit conversion sequences for each of the
5988 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005989 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00005990 if (Candidate.Conversions[ArgIdx].isInitialized()) {
5991 // We already formed a conversion sequence for this parameter during
5992 // template argument deduction.
5993 } else if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005994 // (C++ 13.3.2p3): for F to be a viable function, there shall
5995 // exist for each argument an implicit conversion sequence
5996 // (13.3.3.1) that converts that argument to the corresponding
5997 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005998 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005999 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006000 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006001 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006002 /*InOverloadResolution=*/true,
6003 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006004 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006005 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00006006 if (Candidate.Conversions[ArgIdx].isBad()) {
6007 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006008 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006009 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006010 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006011 } else {
6012 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6013 // argument for which there is no corresponding parameter is
6014 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006015 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006016 }
6017 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006018
Richard Smithf9c59b72017-01-08 21:45:44 +00006019 // C++ [over.best.ics]p4+: (proposed DR resolution)
6020 // If the target is the first parameter of an inherited constructor when
6021 // constructing an object of type C with an argument list that has exactly
6022 // one expression, an implicit conversion sequence cannot be formed if C is
6023 // reference-related to the type that the argument would have after the
6024 // application of the user-defined conversion (if any) and before the final
6025 // standard conversion sequence.
6026 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6027 if (Shadow && Args.size() == 1 && !isa<InitListExpr>(Args.front())) {
6028 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
6029 QualType ConvertedArgumentType = Args.front()->getType();
6030 if (Candidate.Conversions[0].isUserDefined())
6031 ConvertedArgumentType =
6032 Candidate.Conversions[0].UserDefined.After.getFromType();
6033 if (CompareReferenceRelationship(Args.front()->getLocStart(),
6034 Context.getRecordType(Shadow->getParent()),
6035 ConvertedArgumentType, DerivedToBase,
6036 ObjCConversion,
6037 ObjCLifetimeConversion) >= Ref_Related) {
6038 Candidate.Viable = false;
6039 Candidate.FailureKind = ovl_fail_inhctor_slice;
6040 return;
6041 }
6042 }
6043
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006044 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6045 Candidate.Viable = false;
6046 Candidate.FailureKind = ovl_fail_enable_if;
6047 Candidate.DeductionFailure.Data = FailedAttr;
6048 return;
6049 }
Yaxun Liu5b746652016-12-18 05:18:55 +00006050
6051 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6052 Candidate.Viable = false;
6053 Candidate.FailureKind = ovl_fail_ext_disabled;
6054 return;
6055 }
George Burgess IV177399e2017-01-09 04:12:14 +00006056
6057 initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Function, Args);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006058}
6059
Manman Rend2a3cd72016-04-07 19:30:20 +00006060ObjCMethodDecl *
6061Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6062 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6063 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00006064 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00006065
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006066 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6067 bool Match = true;
6068 ObjCMethodDecl *Method = Methods[b];
6069 unsigned NumNamedArgs = Sel.getNumArgs();
6070 // Method might have more arguments than selector indicates. This is due
6071 // to addition of c-style arguments in method.
6072 if (Method->param_size() > NumNamedArgs)
6073 NumNamedArgs = Method->param_size();
6074 if (Args.size() < NumNamedArgs)
6075 continue;
6076
6077 for (unsigned i = 0; i < NumNamedArgs; i++) {
6078 // We can't do any type-checking on a type-dependent argument.
6079 if (Args[i]->isTypeDependent()) {
6080 Match = false;
6081 break;
6082 }
6083
6084 ParmVarDecl *param = Method->parameters()[i];
6085 Expr *argExpr = Args[i];
6086 assert(argExpr && "SelectBestMethod(): missing expression");
6087
6088 // Strip the unbridged-cast placeholder expression off unless it's
6089 // a consumed argument.
6090 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6091 !param->hasAttr<CFConsumedAttr>())
6092 argExpr = stripARCUnbridgedCast(argExpr);
6093
6094 // If the parameter is __unknown_anytype, move on to the next method.
6095 if (param->getType() == Context.UnknownAnyTy) {
6096 Match = false;
6097 break;
6098 }
George Burgess IV45461812015-10-11 20:13:20 +00006099
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006100 ImplicitConversionSequence ConversionState
6101 = TryCopyInitialization(*this, argExpr, param->getType(),
6102 /*SuppressUserConversions*/false,
6103 /*InOverloadResolution=*/true,
6104 /*AllowObjCWritebackConversion=*/
6105 getLangOpts().ObjCAutoRefCount,
6106 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006107 // This function looks for a reasonably-exact match, so we consider
6108 // incompatible pointer conversions to be a failure here.
6109 if (ConversionState.isBad() ||
6110 (ConversionState.isStandard() &&
6111 ConversionState.Standard.Second ==
6112 ICK_Incompatible_Pointer_Conversion)) {
6113 Match = false;
6114 break;
6115 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006116 }
6117 // Promote additional arguments to variadic methods.
6118 if (Match && Method->isVariadic()) {
6119 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6120 if (Args[i]->isTypeDependent()) {
6121 Match = false;
6122 break;
6123 }
6124 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6125 nullptr);
6126 if (Arg.isInvalid()) {
6127 Match = false;
6128 break;
6129 }
6130 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006131 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006132 // Check for extra arguments to non-variadic methods.
6133 if (Args.size() != NumNamedArgs)
6134 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006135 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6136 // Special case when selectors have no argument. In this case, select
6137 // one with the most general result type of 'id'.
6138 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6139 QualType ReturnT = Methods[b]->getReturnType();
6140 if (ReturnT->isObjCIdType())
6141 return Methods[b];
6142 }
6143 }
6144 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006145
6146 if (Match)
6147 return Method;
6148 }
6149 return nullptr;
6150}
6151
George Burgess IV2a6150d2015-10-16 01:17:38 +00006152// specific_attr_iterator iterates over enable_if attributes in reverse, and
6153// enable_if is order-sensitive. As a result, we need to reverse things
6154// sometimes. Size of 4 elements is arbitrary.
6155static SmallVector<EnableIfAttr *, 4>
6156getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6157 SmallVector<EnableIfAttr *, 4> Result;
6158 if (!Function->hasAttrs())
6159 return Result;
6160
6161 const auto &FuncAttrs = Function->getAttrs();
6162 for (Attr *Attr : FuncAttrs)
6163 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6164 Result.push_back(EnableIf);
6165
6166 std::reverse(Result.begin(), Result.end());
6167 return Result;
6168}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006169
George Burgess IV177399e2017-01-09 04:12:14 +00006170static bool
6171convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6172 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6173 bool MissingImplicitThis, Expr *&ConvertedThis,
6174 SmallVectorImpl<Expr *> &ConvertedArgs) {
6175 if (ThisArg) {
6176 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6177 assert(!isa<CXXConstructorDecl>(Method) &&
6178 "Shouldn't have `this` for ctors!");
6179 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6180 ExprResult R = S.PerformObjectArgumentInitialization(
6181 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6182 if (R.isInvalid())
6183 return false;
6184 ConvertedThis = R.get();
6185 } else {
6186 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6187 (void)MD;
6188 assert((MissingImplicitThis || MD->isStatic() ||
6189 isa<CXXConstructorDecl>(MD)) &&
6190 "Expected `this` for non-ctor instance methods");
6191 }
6192 ConvertedThis = nullptr;
6193 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006194
George Burgess IV458b3f32016-08-12 04:19:35 +00006195 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV177399e2017-01-09 04:12:14 +00006196 // user can't refer to them in the function condition.
George Burgess IV53b938d2016-08-12 04:12:31 +00006197 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6198
Nick Lewyckye283c552015-08-25 22:33:16 +00006199 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006200 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006201 ExprResult R;
George Burgess IV177399e2017-01-09 04:12:14 +00006202 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6203 S.Context, Function->getParamDecl(I)),
George Burgess IVe96abf72016-02-24 22:31:14 +00006204 SourceLocation(), Args[I]);
George Burgess IVe96abf72016-02-24 22:31:14 +00006205
George Burgess IV177399e2017-01-09 04:12:14 +00006206 if (R.isInvalid())
6207 return false;
George Burgess IVe96abf72016-02-24 22:31:14 +00006208
George Burgess IVe96abf72016-02-24 22:31:14 +00006209 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006210 }
6211
George Burgess IV177399e2017-01-09 04:12:14 +00006212 if (Trap.hasErrorOccurred())
6213 return false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006214
Nick Lewyckye283c552015-08-25 22:33:16 +00006215 // Push default arguments if needed.
6216 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6217 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6218 ParmVarDecl *P = Function->getParamDecl(i);
George Burgess IV177399e2017-01-09 04:12:14 +00006219 ExprResult R = S.PerformCopyInitialization(
6220 InitializedEntity::InitializeParameter(S.Context,
Nick Lewyckye283c552015-08-25 22:33:16 +00006221 Function->getParamDecl(i)),
6222 SourceLocation(),
6223 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6224 : P->getDefaultArg());
George Burgess IV177399e2017-01-09 04:12:14 +00006225 if (R.isInvalid())
6226 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006227 ConvertedArgs.push_back(R.get());
6228 }
6229
George Burgess IV177399e2017-01-09 04:12:14 +00006230 if (Trap.hasErrorOccurred())
6231 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006232 }
George Burgess IV177399e2017-01-09 04:12:14 +00006233 return true;
6234}
6235
6236EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6237 bool MissingImplicitThis) {
6238 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6239 getOrderedEnableIfAttrs(Function);
6240 if (EnableIfAttrs.empty())
6241 return nullptr;
6242
6243 SFINAETrap Trap(*this);
6244 SmallVector<Expr *, 16> ConvertedArgs;
6245 // FIXME: We should look into making enable_if late-parsed.
6246 Expr *DiscardedThis;
6247 if (!convertArgsForAvailabilityChecks(
6248 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6249 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6250 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006251
George Burgess IV2a6150d2015-10-16 01:17:38 +00006252 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006253 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006254 // FIXME: This doesn't consider value-dependent cases, because doing so is
6255 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006256 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006257 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006258 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006259
6260 if (!Result.isInt() || !Result.getInt().getBoolValue())
6261 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006262 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006263 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006264}
6265
George Burgess IV177399e2017-01-09 04:12:14 +00006266static bool gatherDiagnoseIfAttrs(FunctionDecl *Function, bool ArgDependent,
6267 SmallVectorImpl<DiagnoseIfAttr *> &Errors,
6268 SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal) {
6269 for (auto *DIA : Function->specific_attrs<DiagnoseIfAttr>())
6270 if (ArgDependent == DIA->getArgDependent()) {
6271 if (DIA->isError())
6272 Errors.push_back(DIA);
6273 else
6274 Nonfatal.push_back(DIA);
6275 }
6276
6277 return !Errors.empty() || !Nonfatal.empty();
6278}
6279
6280template <typename CheckFn>
6281static DiagnoseIfAttr *
6282checkDiagnoseIfAttrsWith(const SmallVectorImpl<DiagnoseIfAttr *> &Errors,
6283 SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal,
6284 CheckFn &&IsSuccessful) {
6285 // Note that diagnose_if attributes are late-parsed, so they appear in the
6286 // correct order (unlike enable_if attributes).
6287 auto ErrAttr = llvm::find_if(Errors, IsSuccessful);
6288 if (ErrAttr != Errors.end())
6289 return *ErrAttr;
6290
6291 llvm::erase_if(Nonfatal, [&](DiagnoseIfAttr *A) { return !IsSuccessful(A); });
6292 return nullptr;
6293}
6294
6295DiagnoseIfAttr *
6296Sema::checkArgDependentDiagnoseIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6297 SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal,
6298 bool MissingImplicitThis,
6299 Expr *ThisArg) {
6300 SmallVector<DiagnoseIfAttr *, 4> Errors;
6301 if (!gatherDiagnoseIfAttrs(Function, /*ArgDependent=*/true, Errors, Nonfatal))
6302 return nullptr;
6303
6304 SFINAETrap Trap(*this);
6305 SmallVector<Expr *, 16> ConvertedArgs;
6306 Expr *ConvertedThis;
6307 if (!convertArgsForAvailabilityChecks(*this, Function, ThisArg, Args, Trap,
6308 MissingImplicitThis, ConvertedThis,
6309 ConvertedArgs))
6310 return nullptr;
6311
6312 return checkDiagnoseIfAttrsWith(Errors, Nonfatal, [&](DiagnoseIfAttr *DIA) {
6313 APValue Result;
6314 // It's sane to use the same ConvertedArgs for any redecl of this function,
6315 // since EvaluateWithSubstitution only cares about the position of each
6316 // argument in the arg list, not the ParmVarDecl* it maps to.
6317 if (!DIA->getCond()->EvaluateWithSubstitution(
6318 Result, Context, DIA->getParent(), ConvertedArgs, ConvertedThis))
6319 return false;
6320 return Result.isInt() && Result.getInt().getBoolValue();
6321 });
6322}
6323
6324DiagnoseIfAttr *Sema::checkArgIndependentDiagnoseIf(
6325 FunctionDecl *Function, SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal) {
6326 SmallVector<DiagnoseIfAttr *, 4> Errors;
6327 if (!gatherDiagnoseIfAttrs(Function, /*ArgDependent=*/false, Errors,
6328 Nonfatal))
6329 return nullptr;
6330
6331 return checkDiagnoseIfAttrsWith(Errors, Nonfatal, [&](DiagnoseIfAttr *DIA) {
6332 bool Result;
6333 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6334 Result;
6335 });
6336}
6337
6338void Sema::emitDiagnoseIfDiagnostic(SourceLocation Loc,
6339 const DiagnoseIfAttr *DIA) {
6340 auto Code = DIA->isError() ? diag::err_diagnose_if_succeeded
6341 : diag::warn_diagnose_if_succeeded;
6342 Diag(Loc, Code) << DIA->getMessage();
6343 Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6344 << DIA->getParent() << DIA->getCond()->getSourceRange();
6345}
6346
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006347/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006348/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006349void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006350 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006351 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006352 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006353 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006354 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006355 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006356 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6357 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006358 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006359 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006360 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006361 Args[0]->getType(), Args[0]->Classify(Context),
George Burgess IV177399e2017-01-09 04:12:14 +00006362 Args[0], Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006363 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006364 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006365 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006366 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006367 } else {
John McCalla0296f72010-03-19 07:35:19 +00006368 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006369 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6370 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
George Burgess IV177399e2017-01-09 04:12:14 +00006371 AddMethodTemplateCandidate(
6372 FunTmpl, F.getPair(),
6373 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6374 ExplicitTemplateArgs, Args[0]->getType(),
6375 Args[0]->Classify(Context), Args[0], Args.slice(1), CandidateSet,
6376 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006377 else
John McCalla0296f72010-03-19 07:35:19 +00006378 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006379 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006380 CandidateSet, SuppressUserConversions,
6381 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006382 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006383 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006384}
6385
John McCallf0f1cf02009-11-17 07:50:12 +00006386/// AddMethodCandidate - Adds a named decl (which is some kind of
6387/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006388void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006389 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006390 Expr::Classification ObjectClassification,
George Burgess IV177399e2017-01-09 04:12:14 +00006391 Expr *ThisArg,
Rafael Espindola51629df2013-04-29 19:29:25 +00006392 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006393 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006394 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006395 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006396 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006397
6398 if (isa<UsingShadowDecl>(Decl))
6399 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006400
John McCallf0f1cf02009-11-17 07:50:12 +00006401 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6402 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6403 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006404 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006405 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006406 ObjectType, ObjectClassification,
George Burgess IV177399e2017-01-09 04:12:14 +00006407 ThisArg, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006408 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006409 } else {
John McCalla0296f72010-03-19 07:35:19 +00006410 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006411 ObjectType, ObjectClassification,
George Burgess IV177399e2017-01-09 04:12:14 +00006412 ThisArg, Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006413 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006414 }
6415}
6416
Douglas Gregor436424c2008-11-18 23:14:02 +00006417/// AddMethodCandidate - Adds the given C++ member function to the set
6418/// of candidate functions, using the given function call arguments
6419/// and the object argument (@c Object). For example, in a call
6420/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6421/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6422/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006423/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006424void
John McCalla0296f72010-03-19 07:35:19 +00006425Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006426 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006427 Expr::Classification ObjectClassification,
George Burgess IV177399e2017-01-09 04:12:14 +00006428 Expr *ThisArg, ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006429 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006430 bool SuppressUserConversions,
Richard Smith6eedfe72017-01-09 08:01:21 +00006431 bool PartialOverloading,
6432 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006433 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006434 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006435 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006436 assert(!isa<CXXConstructorDecl>(Method) &&
6437 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006438
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006439 if (!CandidateSet.isNewCandidate(Method))
6440 return;
6441
Richard Smith8b86f2d2013-11-04 01:48:18 +00006442 // C++11 [class.copy]p23: [DR1402]
6443 // A defaulted move assignment operator that is defined as deleted is
6444 // ignored by overload resolution.
6445 if (Method->isDefaulted() && Method->isDeleted() &&
6446 Method->isMoveAssignmentOperator())
6447 return;
6448
Douglas Gregor27381f32009-11-23 12:27:39 +00006449 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006450 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006451
Douglas Gregor436424c2008-11-18 23:14:02 +00006452 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00006453 OverloadCandidate &Candidate =
6454 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00006455 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006456 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006457 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006458 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006459 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006460
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006461 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006462
6463 // (C++ 13.3.2p2): A candidate function having fewer than m
6464 // parameters is viable only if it has an ellipsis in its parameter
6465 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006466 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6467 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006468 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006469 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006470 return;
6471 }
6472
6473 // (C++ 13.3.2p2): A candidate function having more than m parameters
6474 // is viable only if the (m+1)st parameter has a default argument
6475 // (8.3.6). For the purposes of overload resolution, the
6476 // parameter list is truncated on the right, so that there are
6477 // exactly m parameters.
6478 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006479 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006480 // Not enough arguments.
6481 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006482 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006483 return;
6484 }
6485
6486 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006487
John McCall6e9f8f62009-12-03 04:06:58 +00006488 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006489 // The implicit object argument is ignored.
6490 Candidate.IgnoreObjectArgument = true;
6491 else {
6492 // Determine the implicit conversion sequence for the object
6493 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006494 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6495 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6496 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006497 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006498 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006499 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006500 return;
6501 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006502 }
6503
Eli Bendersky291a57e2014-09-25 23:59:08 +00006504 // (CUDA B.1): Check for invalid calls between targets.
6505 if (getLangOpts().CUDA)
6506 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006507 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006508 Candidate.Viable = false;
6509 Candidate.FailureKind = ovl_fail_bad_target;
6510 return;
6511 }
6512
Douglas Gregor436424c2008-11-18 23:14:02 +00006513 // Determine the implicit conversion sequences for each of the
6514 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006515 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006516 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6517 // We already formed a conversion sequence for this parameter during
6518 // template argument deduction.
6519 } else if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006520 // (C++ 13.3.2p3): for F to be a viable function, there shall
6521 // exist for each argument an implicit conversion sequence
6522 // (13.3.3.1) that converts that argument to the corresponding
6523 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006524 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006525 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006526 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006527 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006528 /*InOverloadResolution=*/true,
6529 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006530 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006531 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006532 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006533 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006534 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006535 }
6536 } else {
6537 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6538 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006539 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006540 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006541 }
6542 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006543
6544 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6545 Candidate.Viable = false;
6546 Candidate.FailureKind = ovl_fail_enable_if;
6547 Candidate.DeductionFailure.Data = FailedAttr;
6548 return;
6549 }
George Burgess IV177399e2017-01-09 04:12:14 +00006550
6551 initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Method, Args,
6552 /*MissingImplicitThis=*/!ThisArg, ThisArg);
Douglas Gregor436424c2008-11-18 23:14:02 +00006553}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006554
Douglas Gregor97628d62009-08-21 00:16:32 +00006555/// \brief Add a C++ member function template as a candidate to the candidate
6556/// set, using template argument deduction to produce an appropriate member
6557/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006558void
Douglas Gregor97628d62009-08-21 00:16:32 +00006559Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006560 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006561 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006562 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006563 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006564 Expr::Classification ObjectClassification,
George Burgess IV177399e2017-01-09 04:12:14 +00006565 Expr *ThisArg,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006566 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006567 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006568 bool SuppressUserConversions,
6569 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006570 if (!CandidateSet.isNewCandidate(MethodTmpl))
6571 return;
6572
Douglas Gregor97628d62009-08-21 00:16:32 +00006573 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006574 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006575 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006576 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006577 // candidate functions in the usual way.113) A given name can refer to one
6578 // or more function templates and also to a set of overloaded non-template
6579 // functions. In such a case, the candidate functions generated from each
6580 // function template are combined with the set of non-template candidate
6581 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006582 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006583 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006584 ConversionSequenceList Conversions;
6585 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6586 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6587 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6588 return CheckNonDependentConversions(
6589 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6590 SuppressUserConversions, ActingContext, ObjectType,
6591 ObjectClassification);
6592 })) {
6593 OverloadCandidate &Candidate =
6594 CandidateSet.addCandidate(Conversions.size(), Conversions);
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006595 Candidate.FoundDecl = FoundDecl;
6596 Candidate.Function = MethodTmpl->getTemplatedDecl();
6597 Candidate.Viable = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006598 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006599 Candidate.IgnoreObjectArgument =
6600 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6601 ObjectType.isNull();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006602 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006603 if (Result == TDK_NonDependentConversionFailure)
6604 Candidate.FailureKind = ovl_fail_bad_conversion;
6605 else {
6606 Candidate.FailureKind = ovl_fail_bad_deduction;
6607 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6608 Info);
6609 }
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006610 return;
6611 }
Mike Stump11289f42009-09-09 15:08:12 +00006612
Douglas Gregor97628d62009-08-21 00:16:32 +00006613 // Add the function template specialization produced by template argument
6614 // deduction as a candidate.
6615 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006616 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006617 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006618 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
George Burgess IV177399e2017-01-09 04:12:14 +00006619 ActingContext, ObjectType, ObjectClassification,
6620 /*ThisArg=*/ThisArg, Args, CandidateSet,
Richard Smith6eedfe72017-01-09 08:01:21 +00006621 SuppressUserConversions, PartialOverloading, Conversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00006622}
6623
Douglas Gregor05155d82009-08-21 23:19:43 +00006624/// \brief Add a C++ function template specialization as a candidate
6625/// in the candidate set, using template argument deduction to produce
6626/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006627void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006628Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006629 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006630 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006631 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006632 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006633 bool SuppressUserConversions,
6634 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006635 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6636 return;
6637
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006638 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006639 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006640 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006641 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006642 // candidate functions in the usual way.113) A given name can refer to one
6643 // or more function templates and also to a set of overloaded non-template
6644 // functions. In such a case, the candidate functions generated from each
6645 // function template are combined with the set of non-template candidate
6646 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006647 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006648 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006649 ConversionSequenceList Conversions;
6650 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6651 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6652 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6653 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6654 Args, CandidateSet, Conversions,
6655 SuppressUserConversions);
6656 })) {
6657 OverloadCandidate &Candidate =
6658 CandidateSet.addCandidate(Conversions.size(), Conversions);
John McCalla0296f72010-03-19 07:35:19 +00006659 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006660 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6661 Candidate.Viable = false;
6662 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006663 // Ignore the object argument if there is one, since we don't have an object
6664 // type.
6665 Candidate.IgnoreObjectArgument =
6666 isa<CXXMethodDecl>(Candidate.Function) &&
6667 !isa<CXXConstructorDecl>(Candidate.Function);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006668 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006669 if (Result == TDK_NonDependentConversionFailure)
6670 Candidate.FailureKind = ovl_fail_bad_conversion;
6671 else {
6672 Candidate.FailureKind = ovl_fail_bad_deduction;
6673 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6674 Info);
6675 }
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006676 return;
6677 }
Mike Stump11289f42009-09-09 15:08:12 +00006678
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006679 // Add the function template specialization produced by template argument
6680 // deduction as a candidate.
6681 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006682 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Richard Smith6eedfe72017-01-09 08:01:21 +00006683 SuppressUserConversions, PartialOverloading,
6684 /*AllowExplicit*/false, Conversions);
6685}
6686
6687/// Check that implicit conversion sequences can be formed for each argument
6688/// whose corresponding parameter has a non-dependent type, per DR1391's
6689/// [temp.deduct.call]p10.
6690bool Sema::CheckNonDependentConversions(
6691 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6692 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6693 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6694 CXXRecordDecl *ActingContext, QualType ObjectType,
6695 Expr::Classification ObjectClassification) {
6696 // FIXME: The cases in which we allow explicit conversions for constructor
6697 // arguments never consider calling a constructor template. It's not clear
6698 // that is correct.
6699 const bool AllowExplicit = false;
6700
6701 auto *FD = FunctionTemplate->getTemplatedDecl();
6702 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6703 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6704 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6705
6706 Conversions =
6707 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6708
6709 // Overload resolution is always an unevaluated context.
6710 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6711
6712 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6713 // require that, but this check should never result in a hard error, and
6714 // overload resolution is permitted to sidestep instantiations.
6715 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6716 !ObjectType.isNull()) {
6717 Conversions[0] = TryObjectArgumentInitialization(
6718 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6719 Method, ActingContext);
6720 if (Conversions[0].isBad())
6721 return true;
6722 }
6723
6724 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6725 ++I) {
6726 QualType ParamType = ParamTypes[I];
6727 if (!ParamType->isDependentType()) {
6728 Conversions[ThisConversions + I]
6729 = TryCopyInitialization(*this, Args[I], ParamType,
6730 SuppressUserConversions,
6731 /*InOverloadResolution=*/true,
6732 /*AllowObjCWritebackConversion=*/
6733 getLangOpts().ObjCAutoRefCount,
6734 AllowExplicit);
6735 if (Conversions[ThisConversions + I].isBad())
6736 return true;
6737 }
6738 }
6739
6740 return false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006741}
Mike Stump11289f42009-09-09 15:08:12 +00006742
Douglas Gregor4b60a152013-11-07 22:34:54 +00006743/// Determine whether this is an allowable conversion from the result
6744/// of an explicit conversion operator to the expected type, per C++
6745/// [over.match.conv]p1 and [over.match.ref]p1.
6746///
6747/// \param ConvType The return type of the conversion function.
6748///
6749/// \param ToType The type we are converting to.
6750///
6751/// \param AllowObjCPointerConversion Allow a conversion from one
6752/// Objective-C pointer to another.
6753///
6754/// \returns true if the conversion is allowable, false otherwise.
6755static bool isAllowableExplicitConversion(Sema &S,
6756 QualType ConvType, QualType ToType,
6757 bool AllowObjCPointerConversion) {
6758 QualType ToNonRefType = ToType.getNonReferenceType();
6759
6760 // Easy case: the types are the same.
6761 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6762 return true;
6763
6764 // Allow qualification conversions.
6765 bool ObjCLifetimeConversion;
6766 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6767 ObjCLifetimeConversion))
6768 return true;
6769
6770 // If we're not allowed to consider Objective-C pointer conversions,
6771 // we're done.
6772 if (!AllowObjCPointerConversion)
6773 return false;
6774
6775 // Is this an Objective-C pointer conversion?
6776 bool IncompatibleObjC = false;
6777 QualType ConvertedType;
6778 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6779 IncompatibleObjC);
6780}
6781
Douglas Gregora1f013e2008-11-07 22:36:19 +00006782/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006783/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006784/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006785/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006786/// (which may or may not be the same type as the type that the
6787/// conversion function produces).
6788void
6789Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006790 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006791 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006792 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006793 OverloadCandidateSet& CandidateSet,
6794 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006795 assert(!Conversion->getDescribedFunctionTemplate() &&
6796 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006797 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006798 if (!CandidateSet.isNewCandidate(Conversion))
6799 return;
6800
Richard Smith2a7d4812013-05-04 07:00:32 +00006801 // If the conversion function has an undeduced return type, trigger its
6802 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006803 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006804 if (DeduceReturnType(Conversion, From->getExprLoc()))
6805 return;
6806 ConvType = Conversion->getConversionType().getNonReferenceType();
6807 }
6808
Richard Smith089c3162013-09-21 21:55:46 +00006809 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6810 // operator is only a candidate if its return type is the target type or
6811 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006812 if (Conversion->isExplicit() &&
6813 !isAllowableExplicitConversion(*this, ConvType, ToType,
6814 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006815 return;
6816
Douglas Gregor27381f32009-11-23 12:27:39 +00006817 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006818 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006819
Douglas Gregora1f013e2008-11-07 22:36:19 +00006820 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006821 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006822 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006823 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006824 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006825 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006826 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006827 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006828 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006829 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006830 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006831
Douglas Gregor6affc782010-08-19 15:37:02 +00006832 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006833 // For conversion functions, the function is considered to be a member of
6834 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006835 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006836 //
6837 // Determine the implicit conversion sequence for the implicit
6838 // object parameter.
6839 QualType ImplicitParamType = From->getType();
6840 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6841 ImplicitParamType = FromPtrType->getPointeeType();
6842 CXXRecordDecl *ConversionContext
6843 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006844
Richard Smith0f59cb32015-12-18 21:45:41 +00006845 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6846 *this, CandidateSet.getLocation(), From->getType(),
6847 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006848
John McCall0d1da222010-01-12 00:44:57 +00006849 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006850 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006851 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006852 return;
6853 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006854
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006855 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006856 // derived to base as such conversions are given Conversion Rank. They only
6857 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6858 QualType FromCanon
6859 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6860 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006861 if (FromCanon == ToCanon ||
6862 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006863 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006864 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006865 return;
6866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006867
Douglas Gregora1f013e2008-11-07 22:36:19 +00006868 // To determine what the conversion from the result of calling the
6869 // conversion function to the type we're eventually trying to
6870 // convert to (ToType), we need to synthesize a call to the
6871 // conversion function and attempt copy initialization from it. This
6872 // makes sure that we get the right semantics with respect to
6873 // lvalues/rvalues and the type. Fortunately, we can allocate this
6874 // call on the stack and we don't need its arguments to be
6875 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006876 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006877 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006878 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6879 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006880 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006881 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006882
Richard Smith48d24642011-07-13 22:53:21 +00006883 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006884 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006885 Candidate.Viable = false;
6886 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6887 return;
6888 }
6889
Richard Smith48d24642011-07-13 22:53:21 +00006890 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006891
Mike Stump11289f42009-09-09 15:08:12 +00006892 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006893 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6894 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006895 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006896 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006897 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006898 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006899 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006900 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006901 /*InOverloadResolution=*/false,
6902 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006903
John McCall0d1da222010-01-12 00:44:57 +00006904 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006905 case ImplicitConversionSequence::StandardConversion:
6906 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006907
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006908 // C++ [over.ics.user]p3:
6909 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006910 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006911 // shall have exact match rank.
6912 if (Conversion->getPrimaryTemplate() &&
6913 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6914 Candidate.Viable = false;
6915 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006916 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006918
Douglas Gregorcba72b12011-01-21 05:18:22 +00006919 // C++0x [dcl.init.ref]p5:
6920 // In the second case, if the reference is an rvalue reference and
6921 // the second standard conversion sequence of the user-defined
6922 // conversion sequence includes an lvalue-to-rvalue conversion, the
6923 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006924 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006925 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6926 Candidate.Viable = false;
6927 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006928 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006929 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006930 break;
6931
6932 case ImplicitConversionSequence::BadConversion:
6933 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006934 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006935 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006936
6937 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006938 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006939 "Can only end up with a standard conversion sequence or failure");
6940 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006941
Craig Topper5fc8fc22014-08-27 06:28:36 +00006942 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006943 Candidate.Viable = false;
6944 Candidate.FailureKind = ovl_fail_enable_if;
6945 Candidate.DeductionFailure.Data = FailedAttr;
6946 return;
6947 }
George Burgess IV177399e2017-01-09 04:12:14 +00006948
6949 initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Conversion, None, false, From);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006950}
6951
Douglas Gregor05155d82009-08-21 23:19:43 +00006952/// \brief Adds a conversion function template specialization
6953/// candidate to the overload set, using template argument deduction
6954/// to deduce the template arguments of the conversion function
6955/// template from the type that we are converting to (C++
6956/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006957void
Douglas Gregor05155d82009-08-21 23:19:43 +00006958Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006959 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006960 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006961 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006962 OverloadCandidateSet &CandidateSet,
6963 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006964 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6965 "Only conversion function templates permitted here");
6966
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006967 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6968 return;
6969
Craig Toppere6706e42012-09-19 02:26:47 +00006970 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006971 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006972 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006973 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006974 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006975 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006976 Candidate.FoundDecl = FoundDecl;
6977 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6978 Candidate.Viable = false;
6979 Candidate.FailureKind = ovl_fail_bad_deduction;
6980 Candidate.IsSurrogate = false;
6981 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006982 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006983 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006984 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006985 return;
6986 }
Mike Stump11289f42009-09-09 15:08:12 +00006987
Douglas Gregor05155d82009-08-21 23:19:43 +00006988 // Add the conversion function template specialization produced by
6989 // template argument deduction as a candidate.
6990 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006991 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006992 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006993}
6994
Douglas Gregorab7897a2008-11-19 22:57:39 +00006995/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6996/// converts the given @c Object to a function pointer via the
6997/// conversion function @c Conversion, and then attempts to call it
6998/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6999/// the type of function that we'll eventually be calling.
7000void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00007001 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00007002 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007003 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00007004 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007005 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00007006 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00007007 if (!CandidateSet.isNewCandidate(Conversion))
7008 return;
7009
Douglas Gregor27381f32009-11-23 12:27:39 +00007010 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00007011 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007012
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007013 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00007014 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00007015 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007016 Candidate.Surrogate = Conversion;
7017 Candidate.Viable = true;
7018 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007019 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00007020 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007021
7022 // Determine the implicit conversion sequence for the implicit
7023 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00007024 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7025 *this, CandidateSet.getLocation(), Object->getType(),
7026 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00007027 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007028 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007029 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00007030 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007031 return;
7032 }
7033
7034 // The first conversion is actually a user-defined conversion whose
7035 // first conversion is ObjectInit's standard conversion (which is
7036 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00007037 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007038 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00007039 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007040 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007041 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00007042 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00007043 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00007044 = Candidate.Conversions[0].UserDefined.Before;
7045 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7046
Mike Stump11289f42009-09-09 15:08:12 +00007047 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007048 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007049
7050 // (C++ 13.3.2p2): A candidate function having fewer than m
7051 // parameters is viable only if it has an ellipsis in its parameter
7052 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007053 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007054 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007055 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007056 return;
7057 }
7058
7059 // Function types don't have any default arguments, so just check if
7060 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007061 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007062 // Not enough arguments.
7063 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007064 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007065 return;
7066 }
7067
7068 // Determine the implicit conversion sequences for each of the
7069 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00007070 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007071 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007072 // (C++ 13.3.2p3): for F to be a viable function, there shall
7073 // exist for each argument an implicit conversion sequence
7074 // (13.3.3.1) that converts that argument to the corresponding
7075 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00007076 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00007077 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007078 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00007079 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00007080 /*InOverloadResolution=*/false,
7081 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007082 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00007083 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007084 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007085 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007086 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007087 }
7088 } else {
7089 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7090 // argument for which there is no corresponding parameter is
7091 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00007092 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007093 }
7094 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007095
Craig Topper5fc8fc22014-08-27 06:28:36 +00007096 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007097 Candidate.Viable = false;
7098 Candidate.FailureKind = ovl_fail_enable_if;
7099 Candidate.DeductionFailure.Data = FailedAttr;
7100 return;
7101 }
George Burgess IV177399e2017-01-09 04:12:14 +00007102
7103 initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Conversion, None);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007104}
7105
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007106/// \brief Add overload candidates for overloaded operators that are
7107/// member functions.
7108///
7109/// Add the overloaded operator candidates that are member functions
7110/// for the operator Op that was used in an operator expression such
7111/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7112/// CandidateSet will store the added overload candidates. (C++
7113/// [over.match.oper]).
7114void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7115 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00007116 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007117 OverloadCandidateSet& CandidateSet,
7118 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00007119 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7120
7121 // C++ [over.match.oper]p3:
7122 // For a unary operator @ with an operand of a type whose
7123 // cv-unqualified version is T1, and for a binary operator @ with
7124 // a left operand of a type whose cv-unqualified version is T1 and
7125 // a right operand of a type whose cv-unqualified version is T2,
7126 // three sets of candidate functions, designated member
7127 // candidates, non-member candidates and built-in candidates, are
7128 // constructed as follows:
7129 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00007130
Richard Smith0feaf0c2013-04-20 12:41:22 +00007131 // -- If T1 is a complete class type or a class currently being
7132 // defined, the set of member candidates is the result of the
7133 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7134 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007135 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00007136 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00007137 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00007138 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00007139 // If the type is neither complete nor being defined, bail out now.
7140 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007141 return;
Mike Stump11289f42009-09-09 15:08:12 +00007142
John McCall27b18f82009-11-17 02:14:36 +00007143 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7144 LookupQualifiedName(Operators, T1Rec->getDecl());
7145 Operators.suppressDiagnostics();
7146
Mike Stump11289f42009-09-09 15:08:12 +00007147 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007148 OperEnd = Operators.end();
7149 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00007150 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00007151 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
George Burgess IV177399e2017-01-09 04:12:14 +00007152 Args[0]->Classify(Context), Args[0], Args.slice(1),
7153 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00007154 }
Douglas Gregor436424c2008-11-18 23:14:02 +00007155}
7156
Douglas Gregora11693b2008-11-12 17:17:38 +00007157/// AddBuiltinCandidate - Add a candidate for a built-in
7158/// operator. ResultTy and ParamTys are the result and parameter types
7159/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00007160/// arguments being passed to the candidate. IsAssignmentOperator
7161/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00007162/// operator. NumContextualBoolArguments is the number of arguments
7163/// (at the beginning of the argument list) that will be contextually
7164/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00007165void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00007166 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00007167 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007168 bool IsAssignmentOperator,
7169 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00007170 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00007171 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007172
Douglas Gregora11693b2008-11-12 17:17:38 +00007173 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00007174 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00007175 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7176 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00007177 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007178 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00007179 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007180 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00007181 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
7182
7183 // Determine the implicit conversion sequences for each of the
7184 // arguments.
7185 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00007186 Candidate.ExplicitCallArguments = Args.size();
7187 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00007188 // C++ [over.match.oper]p4:
7189 // For the built-in assignment operators, conversions of the
7190 // left operand are restricted as follows:
7191 // -- no temporaries are introduced to hold the left operand, and
7192 // -- no user-defined conversions are applied to the left
7193 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00007194 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00007195 //
7196 // We block these conversions by turning off user-defined
7197 // conversions, since that is the only way that initialization of
7198 // a reference to a non-class type can occur from something that
7199 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007200 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00007201 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00007202 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00007203 Candidate.Conversions[ArgIdx]
7204 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007205 } else {
Mike Stump11289f42009-09-09 15:08:12 +00007206 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007207 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00007208 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00007209 /*InOverloadResolution=*/false,
7210 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007211 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007212 }
John McCall0d1da222010-01-12 00:44:57 +00007213 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007214 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007215 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00007216 break;
7217 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007218 }
7219}
7220
Craig Toppercd7b0332013-07-01 06:29:40 +00007221namespace {
7222
Douglas Gregora11693b2008-11-12 17:17:38 +00007223/// BuiltinCandidateTypeSet - A set of types that will be used for the
7224/// candidate operator functions for built-in operators (C++
7225/// [over.built]). The types are separated into pointer types and
7226/// enumeration types.
7227class BuiltinCandidateTypeSet {
7228 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00007229 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7230 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00007231
7232 /// PointerTypes - The set of pointer types that will be used in the
7233 /// built-in candidates.
7234 TypeSet PointerTypes;
7235
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007236 /// MemberPointerTypes - The set of member pointer types that will be
7237 /// used in the built-in candidates.
7238 TypeSet MemberPointerTypes;
7239
Douglas Gregora11693b2008-11-12 17:17:38 +00007240 /// EnumerationTypes - The set of enumeration types that will be
7241 /// used in the built-in candidates.
7242 TypeSet EnumerationTypes;
7243
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007244 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007245 /// candidates.
7246 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00007247
7248 /// \brief A flag indicating non-record types are viable candidates
7249 bool HasNonRecordTypes;
7250
7251 /// \brief A flag indicating whether either arithmetic or enumeration types
7252 /// were present in the candidate set.
7253 bool HasArithmeticOrEnumeralTypes;
7254
Douglas Gregor80af3132011-05-21 23:15:46 +00007255 /// \brief A flag indicating whether the nullptr type was present in the
7256 /// candidate set.
7257 bool HasNullPtrType;
7258
Douglas Gregor8a2e6012009-08-24 15:23:48 +00007259 /// Sema - The semantic analysis instance where we are building the
7260 /// candidate type set.
7261 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00007262
Douglas Gregora11693b2008-11-12 17:17:38 +00007263 /// Context - The AST context in which we will build the type sets.
7264 ASTContext &Context;
7265
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007266 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7267 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007268 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00007269
7270public:
7271 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007272 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007273
Mike Stump11289f42009-09-09 15:08:12 +00007274 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007275 : HasNonRecordTypes(false),
7276 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007277 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007278 SemaRef(SemaRef),
7279 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007280
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007281 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007282 SourceLocation Loc,
7283 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007284 bool AllowExplicitConversions,
7285 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007286
7287 /// pointer_begin - First pointer type found;
7288 iterator pointer_begin() { return PointerTypes.begin(); }
7289
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007290 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007291 iterator pointer_end() { return PointerTypes.end(); }
7292
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007293 /// member_pointer_begin - First member pointer type found;
7294 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7295
7296 /// member_pointer_end - Past the last member pointer type found;
7297 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7298
Douglas Gregora11693b2008-11-12 17:17:38 +00007299 /// enumeration_begin - First enumeration type found;
7300 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7301
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007302 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007303 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007304
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007305 iterator vector_begin() { return VectorTypes.begin(); }
7306 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007307
7308 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7309 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007310 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007311};
7312
Craig Toppercd7b0332013-07-01 06:29:40 +00007313} // end anonymous namespace
7314
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007315/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007316/// the set of pointer types along with any more-qualified variants of
7317/// that type. For example, if @p Ty is "int const *", this routine
7318/// will add "int const *", "int const volatile *", "int const
7319/// restrict *", and "int const volatile restrict *" to the set of
7320/// pointer types. Returns true if the add of @p Ty itself succeeded,
7321/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007322///
7323/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007324bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007325BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7326 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007327
Douglas Gregora11693b2008-11-12 17:17:38 +00007328 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007329 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007330 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007331
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007332 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007333 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007334 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007335 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007336 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7337 PointeeTy = PTy->getPointeeType();
7338 buildObjCPtr = true;
7339 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007340 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007341 }
7342
Sebastian Redl4990a632009-11-18 20:39:26 +00007343 // Don't add qualified variants of arrays. For one, they're not allowed
7344 // (the qualifier would sink to the element type), and for another, the
7345 // only overload situation where it matters is subscript or pointer +- int,
7346 // and those shouldn't have qualifier variants anyway.
7347 if (PointeeTy->isArrayType())
7348 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007349
John McCall8ccfcb52009-09-24 19:53:00 +00007350 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007351 bool hasVolatile = VisibleQuals.hasVolatile();
7352 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007353
John McCall8ccfcb52009-09-24 19:53:00 +00007354 // Iterate through all strict supersets of BaseCVR.
7355 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7356 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007357 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007358 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007359
7360 // Skip over restrict if no restrict found anywhere in the types, or if
7361 // the type cannot be restrict-qualified.
7362 if ((CVR & Qualifiers::Restrict) &&
7363 (!hasRestrict ||
7364 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7365 continue;
7366
7367 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007368 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007369
7370 // Build qualified pointer type.
7371 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007372 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007373 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007374 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007375 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7376
7377 // Insert qualified pointer type.
7378 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007379 }
7380
7381 return true;
7382}
7383
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007384/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7385/// to the set of pointer types along with any more-qualified variants of
7386/// that type. For example, if @p Ty is "int const *", this routine
7387/// will add "int const *", "int const volatile *", "int const
7388/// restrict *", and "int const volatile restrict *" to the set of
7389/// pointer types. Returns true if the add of @p Ty itself succeeded,
7390/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007391///
7392/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007393bool
7394BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7395 QualType Ty) {
7396 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007397 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007398 return false;
7399
John McCall8ccfcb52009-09-24 19:53:00 +00007400 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7401 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007402
John McCall8ccfcb52009-09-24 19:53:00 +00007403 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007404 // Don't add qualified variants of arrays. For one, they're not allowed
7405 // (the qualifier would sink to the element type), and for another, the
7406 // only overload situation where it matters is subscript or pointer +- int,
7407 // and those shouldn't have qualifier variants anyway.
7408 if (PointeeTy->isArrayType())
7409 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007410 const Type *ClassTy = PointerTy->getClass();
7411
7412 // Iterate through all strict supersets of the pointee type's CVR
7413 // qualifiers.
7414 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7415 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7416 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007417
John McCall8ccfcb52009-09-24 19:53:00 +00007418 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007419 MemberPointerTypes.insert(
7420 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007421 }
7422
7423 return true;
7424}
7425
Douglas Gregora11693b2008-11-12 17:17:38 +00007426/// AddTypesConvertedFrom - Add each of the types to which the type @p
7427/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007428/// primarily interested in pointer types and enumeration types. We also
7429/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007430/// AllowUserConversions is true if we should look at the conversion
7431/// functions of a class type, and AllowExplicitConversions if we
7432/// should also include the explicit conversion functions of a class
7433/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007434void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007435BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007436 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007437 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007438 bool AllowExplicitConversions,
7439 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007440 // Only deal with canonical types.
7441 Ty = Context.getCanonicalType(Ty);
7442
7443 // Look through reference types; they aren't part of the type of an
7444 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007445 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007446 Ty = RefTy->getPointeeType();
7447
John McCall33ddac02011-01-19 10:06:00 +00007448 // If we're dealing with an array type, decay to the pointer.
7449 if (Ty->isArrayType())
7450 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7451
7452 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007453 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007454
Chandler Carruth00a38332010-12-13 01:44:01 +00007455 // Flag if we ever add a non-record type.
7456 const RecordType *TyRec = Ty->getAs<RecordType>();
7457 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7458
Chandler Carruth00a38332010-12-13 01:44:01 +00007459 // Flag if we encounter an arithmetic type.
7460 HasArithmeticOrEnumeralTypes =
7461 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7462
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007463 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7464 PointerTypes.insert(Ty);
7465 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007466 // Insert our type, and its more-qualified variants, into the set
7467 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007468 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007469 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007470 } else if (Ty->isMemberPointerType()) {
7471 // Member pointers are far easier, since the pointee can't be converted.
7472 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7473 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007474 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007475 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007476 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007477 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007478 // We treat vector types as arithmetic types in many contexts as an
7479 // extension.
7480 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007481 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007482 } else if (Ty->isNullPtrType()) {
7483 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007484 } else if (AllowUserConversions && TyRec) {
7485 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007486 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007487 return;
Mike Stump11289f42009-09-09 15:08:12 +00007488
Chandler Carruth00a38332010-12-13 01:44:01 +00007489 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007490 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007491 if (isa<UsingShadowDecl>(D))
7492 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007493
Chandler Carruth00a38332010-12-13 01:44:01 +00007494 // Skip conversion function templates; they don't tell us anything
7495 // about which builtin types we can convert to.
7496 if (isa<FunctionTemplateDecl>(D))
7497 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007498
Chandler Carruth00a38332010-12-13 01:44:01 +00007499 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7500 if (AllowExplicitConversions || !Conv->isExplicit()) {
7501 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7502 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007503 }
7504 }
7505 }
7506}
7507
Douglas Gregor84605ae2009-08-24 13:43:27 +00007508/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7509/// the volatile- and non-volatile-qualified assignment operators for the
7510/// given type to the candidate set.
7511static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7512 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007513 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007514 OverloadCandidateSet &CandidateSet) {
7515 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007516
Douglas Gregor84605ae2009-08-24 13:43:27 +00007517 // T& operator=(T&, T)
7518 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7519 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007520 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007521 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007522
Douglas Gregor84605ae2009-08-24 13:43:27 +00007523 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7524 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007525 ParamTypes[0]
7526 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007527 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007528 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007529 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007530 }
7531}
Mike Stump11289f42009-09-09 15:08:12 +00007532
Sebastian Redl1054fae2009-10-25 17:03:50 +00007533/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7534/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007535static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7536 Qualifiers VRQuals;
7537 const RecordType *TyRec;
7538 if (const MemberPointerType *RHSMPType =
7539 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007540 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007541 else
7542 TyRec = ArgExpr->getType()->getAs<RecordType>();
7543 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007544 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007545 VRQuals.addVolatile();
7546 VRQuals.addRestrict();
7547 return VRQuals;
7548 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007549
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007550 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007551 if (!ClassDecl->hasDefinition())
7552 return VRQuals;
7553
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007554 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007555 if (isa<UsingShadowDecl>(D))
7556 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7557 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007558 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7559 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7560 CanTy = ResTypeRef->getPointeeType();
7561 // Need to go down the pointer/mempointer chain and add qualifiers
7562 // as see them.
7563 bool done = false;
7564 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007565 if (CanTy.isRestrictQualified())
7566 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007567 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7568 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007569 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007570 CanTy->getAs<MemberPointerType>())
7571 CanTy = ResTypeMPtr->getPointeeType();
7572 else
7573 done = true;
7574 if (CanTy.isVolatileQualified())
7575 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007576 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7577 return VRQuals;
7578 }
7579 }
7580 }
7581 return VRQuals;
7582}
John McCall52872982010-11-13 05:51:15 +00007583
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007584namespace {
John McCall52872982010-11-13 05:51:15 +00007585
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007586/// \brief Helper class to manage the addition of builtin operator overload
7587/// candidates. It provides shared state and utility methods used throughout
7588/// the process, as well as a helper method to add each group of builtin
7589/// operator overloads from the standard to a candidate set.
7590class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007591 // Common instance state available to all overload candidate addition methods.
7592 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007593 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007594 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007595 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007596 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007597 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007598
Chandler Carruthc6586e52010-12-12 10:35:00 +00007599 // Define some constants used to index and iterate over the arithemetic types
7600 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007601 // The "promoted arithmetic types" are the arithmetic
7602 // types are that preserved by promotion (C++ [over.built]p2).
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007603 static const unsigned FirstIntegralType = 4;
7604 static const unsigned LastIntegralType = 21;
7605 static const unsigned FirstPromotedIntegralType = 4,
7606 LastPromotedIntegralType = 12;
John McCall52872982010-11-13 05:51:15 +00007607 static const unsigned FirstPromotedArithmeticType = 0,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007608 LastPromotedArithmeticType = 12;
7609 static const unsigned NumArithmeticTypes = 21;
John McCall52872982010-11-13 05:51:15 +00007610
Chandler Carruthc6586e52010-12-12 10:35:00 +00007611 /// \brief Get the canonical type for a given arithmetic type index.
7612 CanQualType getArithmeticType(unsigned index) {
7613 assert(index < NumArithmeticTypes);
7614 static CanQualType ASTContext::* const
7615 ArithmeticTypes[NumArithmeticTypes] = {
7616 // Start of promoted types.
7617 &ASTContext::FloatTy,
7618 &ASTContext::DoubleTy,
7619 &ASTContext::LongDoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007620 &ASTContext::Float128Ty,
John McCall52872982010-11-13 05:51:15 +00007621
Chandler Carruthc6586e52010-12-12 10:35:00 +00007622 // Start of integral types.
7623 &ASTContext::IntTy,
7624 &ASTContext::LongTy,
7625 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007626 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007627 &ASTContext::UnsignedIntTy,
7628 &ASTContext::UnsignedLongTy,
7629 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007630 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007631 // End of promoted types.
7632
7633 &ASTContext::BoolTy,
7634 &ASTContext::CharTy,
7635 &ASTContext::WCharTy,
7636 &ASTContext::Char16Ty,
7637 &ASTContext::Char32Ty,
7638 &ASTContext::SignedCharTy,
7639 &ASTContext::ShortTy,
7640 &ASTContext::UnsignedCharTy,
7641 &ASTContext::UnsignedShortTy,
7642 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007643 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007644 };
7645 return S.Context.*ArithmeticTypes[index];
7646 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007647
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007648 /// \brief Gets the canonical type resulting from the usual arithemetic
7649 /// converions for the given arithmetic types.
7650 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7651 // Accelerator table for performing the usual arithmetic conversions.
7652 // The rules are basically:
7653 // - if either is floating-point, use the wider floating-point
7654 // - if same signedness, use the higher rank
7655 // - if same size, use unsigned of the higher rank
7656 // - use the larger type
7657 // These rules, together with the axiom that higher ranks are
7658 // never smaller, are sufficient to precompute all of these results
7659 // *except* when dealing with signed types of higher rank.
7660 // (we could precompute SLL x UI for all known platforms, but it's
7661 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007662 // We assume that int128 has a higher rank than long long on all platforms.
George Burgess IVf23ce362016-04-29 21:32:53 +00007663 enum PromotedType : int8_t {
Richard Smith521ecc12012-06-10 08:00:26 +00007664 Dep=-1,
7665 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007666 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007667 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007668 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007669/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7670/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7671/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7672/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7673/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7674/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7675/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7676/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7677/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7678/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7679/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007680 };
7681
7682 assert(L < LastPromotedArithmeticType);
7683 assert(R < LastPromotedArithmeticType);
7684 int Idx = ConversionsTable[L][R];
7685
7686 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007687 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007688
7689 // Slow path: we need to compare widths.
7690 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007691 CanQualType LT = getArithmeticType(L),
7692 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007693 unsigned LW = S.Context.getIntWidth(LT),
7694 RW = S.Context.getIntWidth(RT);
7695
7696 // If they're different widths, use the signed type.
7697 if (LW > RW) return LT;
7698 else if (LW < RW) return RT;
7699
7700 // Otherwise, use the unsigned type of the signed type's rank.
7701 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7702 assert(L == SLL || R == SLL);
7703 return S.Context.UnsignedLongLongTy;
7704 }
7705
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007706 /// \brief Helper method to factor out the common pattern of adding overloads
7707 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007708 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007709 bool HasVolatile,
7710 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007711 QualType ParamTypes[2] = {
7712 S.Context.getLValueReferenceType(CandidateTy),
7713 S.Context.IntTy
7714 };
7715
7716 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007717 if (Args.size() == 1)
7718 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007719 else
Richard Smithe54c3072013-05-05 15:51:06 +00007720 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007721
7722 // Use a heuristic to reduce number of builtin candidates in the set:
7723 // add volatile version only if there are conversions to a volatile type.
7724 if (HasVolatile) {
7725 ParamTypes[0] =
7726 S.Context.getLValueReferenceType(
7727 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007728 if (Args.size() == 1)
7729 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007730 else
Richard Smithe54c3072013-05-05 15:51:06 +00007731 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007732 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007733
7734 // Add restrict version only if there are conversions to a restrict type
7735 // and our candidate type is a non-restrict-qualified pointer.
7736 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7737 !CandidateTy.isRestrictQualified()) {
7738 ParamTypes[0]
7739 = S.Context.getLValueReferenceType(
7740 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007741 if (Args.size() == 1)
7742 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007743 else
Richard Smithe54c3072013-05-05 15:51:06 +00007744 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007745
7746 if (HasVolatile) {
7747 ParamTypes[0]
7748 = S.Context.getLValueReferenceType(
7749 S.Context.getCVRQualifiedType(CandidateTy,
7750 (Qualifiers::Volatile |
7751 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007752 if (Args.size() == 1)
7753 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007754 else
Richard Smithe54c3072013-05-05 15:51:06 +00007755 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007756 }
7757 }
7758
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007759 }
7760
7761public:
7762 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007763 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007764 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007765 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007766 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007767 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007768 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007769 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007770 HasArithmeticOrEnumeralCandidateType(
7771 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007772 CandidateTypes(CandidateTypes),
7773 CandidateSet(CandidateSet) {
7774 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007775 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007776 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007777 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007778 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007779 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007780 assert(getArithmeticType(FirstPromotedArithmeticType)
7781 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007782 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007783 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007784 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007785 "Invalid last promoted arithmetic type");
7786 }
7787
7788 // C++ [over.built]p3:
7789 //
7790 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7791 // is either volatile or empty, there exist candidate operator
7792 // functions of the form
7793 //
7794 // VQ T& operator++(VQ T&);
7795 // T operator++(VQ T&, int);
7796 //
7797 // C++ [over.built]p4:
7798 //
7799 // For every pair (T, VQ), where T is an arithmetic type other
7800 // than bool, and VQ is either volatile or empty, there exist
7801 // candidate operator functions of the form
7802 //
7803 // VQ T& operator--(VQ T&);
7804 // T operator--(VQ T&, int);
7805 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007806 if (!HasArithmeticOrEnumeralCandidateType)
7807 return;
7808
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007809 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7810 Arith < NumArithmeticTypes; ++Arith) {
7811 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007812 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007813 VisibleTypeConversionsQuals.hasVolatile(),
7814 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007815 }
7816 }
7817
7818 // C++ [over.built]p5:
7819 //
7820 // For every pair (T, VQ), where T is a cv-qualified or
7821 // cv-unqualified object type, and VQ is either volatile or
7822 // empty, there exist candidate operator functions of the form
7823 //
7824 // T*VQ& operator++(T*VQ&);
7825 // T*VQ& operator--(T*VQ&);
7826 // T* operator++(T*VQ&, int);
7827 // T* operator--(T*VQ&, int);
7828 void addPlusPlusMinusMinusPointerOverloads() {
7829 for (BuiltinCandidateTypeSet::iterator
7830 Ptr = CandidateTypes[0].pointer_begin(),
7831 PtrEnd = CandidateTypes[0].pointer_end();
7832 Ptr != PtrEnd; ++Ptr) {
7833 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007834 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007835 continue;
7836
7837 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007838 (!(*Ptr).isVolatileQualified() &&
7839 VisibleTypeConversionsQuals.hasVolatile()),
7840 (!(*Ptr).isRestrictQualified() &&
7841 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007842 }
7843 }
7844
7845 // C++ [over.built]p6:
7846 // For every cv-qualified or cv-unqualified object type T, there
7847 // exist candidate operator functions of the form
7848 //
7849 // T& operator*(T*);
7850 //
7851 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007852 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007853 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007854 // T& operator*(T*);
7855 void addUnaryStarPointerOverloads() {
7856 for (BuiltinCandidateTypeSet::iterator
7857 Ptr = CandidateTypes[0].pointer_begin(),
7858 PtrEnd = CandidateTypes[0].pointer_end();
7859 Ptr != PtrEnd; ++Ptr) {
7860 QualType ParamTy = *Ptr;
7861 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007862 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7863 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007864
Douglas Gregor02824322011-01-26 19:30:28 +00007865 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7866 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7867 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007868
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007869 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007870 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007871 }
7872 }
7873
7874 // C++ [over.built]p9:
7875 // For every promoted arithmetic type T, there exist candidate
7876 // operator functions of the form
7877 //
7878 // T operator+(T);
7879 // T operator-(T);
7880 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007881 if (!HasArithmeticOrEnumeralCandidateType)
7882 return;
7883
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007884 for (unsigned Arith = FirstPromotedArithmeticType;
7885 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007886 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007887 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007888 }
7889
7890 // Extension: We also add these operators for vector types.
7891 for (BuiltinCandidateTypeSet::iterator
7892 Vec = CandidateTypes[0].vector_begin(),
7893 VecEnd = CandidateTypes[0].vector_end();
7894 Vec != VecEnd; ++Vec) {
7895 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007896 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007897 }
7898 }
7899
7900 // C++ [over.built]p8:
7901 // For every type T, there exist candidate operator functions of
7902 // the form
7903 //
7904 // T* operator+(T*);
7905 void addUnaryPlusPointerOverloads() {
7906 for (BuiltinCandidateTypeSet::iterator
7907 Ptr = CandidateTypes[0].pointer_begin(),
7908 PtrEnd = CandidateTypes[0].pointer_end();
7909 Ptr != PtrEnd; ++Ptr) {
7910 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007911 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007912 }
7913 }
7914
7915 // C++ [over.built]p10:
7916 // For every promoted integral type T, there exist candidate
7917 // operator functions of the form
7918 //
7919 // T operator~(T);
7920 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007921 if (!HasArithmeticOrEnumeralCandidateType)
7922 return;
7923
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007924 for (unsigned Int = FirstPromotedIntegralType;
7925 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007926 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007927 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007928 }
7929
7930 // Extension: We also add this operator for vector types.
7931 for (BuiltinCandidateTypeSet::iterator
7932 Vec = CandidateTypes[0].vector_begin(),
7933 VecEnd = CandidateTypes[0].vector_end();
7934 Vec != VecEnd; ++Vec) {
7935 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007936 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007937 }
7938 }
7939
7940 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007941 // For every pointer to member type T or type std::nullptr_t, there
7942 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007943 //
7944 // bool operator==(T,T);
7945 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007946 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007947 /// Set of (canonical) types that we've already handled.
7948 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7949
Richard Smithe54c3072013-05-05 15:51:06 +00007950 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007951 for (BuiltinCandidateTypeSet::iterator
7952 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7953 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7954 MemPtr != MemPtrEnd;
7955 ++MemPtr) {
7956 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007957 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007958 continue;
7959
7960 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007961 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007962 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007963
7964 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7965 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7966 if (AddedTypes.insert(NullPtrTy).second) {
7967 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7968 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7969 CandidateSet);
7970 }
7971 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007972 }
7973 }
7974
7975 // C++ [over.built]p15:
7976 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007977 // For every T, where T is an enumeration type or a pointer type,
7978 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007979 //
7980 // bool operator<(T, T);
7981 // bool operator>(T, T);
7982 // bool operator<=(T, T);
7983 // bool operator>=(T, T);
7984 // bool operator==(T, T);
7985 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007986 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007987 // C++ [over.match.oper]p3:
7988 // [...]the built-in candidates include all of the candidate operator
7989 // functions defined in 13.6 that, compared to the given operator, [...]
7990 // do not have the same parameter-type-list as any non-template non-member
7991 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007992 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007993 // Note that in practice, this only affects enumeration types because there
7994 // aren't any built-in candidates of record type, and a user-defined operator
7995 // must have an operand of record or enumeration type. Also, the only other
7996 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007997 // cannot be overloaded for enumeration types, so this is the only place
7998 // where we must suppress candidates like this.
7999 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8000 UserDefinedBinaryOperators;
8001
Richard Smithe54c3072013-05-05 15:51:06 +00008002 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008003 if (CandidateTypes[ArgIdx].enumeration_begin() !=
8004 CandidateTypes[ArgIdx].enumeration_end()) {
8005 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8006 CEnd = CandidateSet.end();
8007 C != CEnd; ++C) {
8008 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8009 continue;
8010
Eli Friedman14f082b2012-09-18 21:52:24 +00008011 if (C->Function->isFunctionTemplateSpecialization())
8012 continue;
8013
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008014 QualType FirstParamType =
8015 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8016 QualType SecondParamType =
8017 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8018
8019 // Skip if either parameter isn't of enumeral type.
8020 if (!FirstParamType->isEnumeralType() ||
8021 !SecondParamType->isEnumeralType())
8022 continue;
8023
8024 // Add this operator to the set of known user-defined operators.
8025 UserDefinedBinaryOperators.insert(
8026 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8027 S.Context.getCanonicalType(SecondParamType)));
8028 }
8029 }
8030 }
8031
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008032 /// Set of (canonical) types that we've already handled.
8033 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8034
Richard Smithe54c3072013-05-05 15:51:06 +00008035 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008036 for (BuiltinCandidateTypeSet::iterator
8037 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8038 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8039 Ptr != PtrEnd; ++Ptr) {
8040 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008041 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008042 continue;
8043
8044 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008045 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008046 }
8047 for (BuiltinCandidateTypeSet::iterator
8048 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8049 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8050 Enum != EnumEnd; ++Enum) {
8051 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8052
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008053 // Don't add the same builtin candidate twice, or if a user defined
8054 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00008055 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008056 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8057 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008058 continue;
8059
8060 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008061 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008062 }
8063 }
8064 }
8065
8066 // C++ [over.built]p13:
8067 //
8068 // For every cv-qualified or cv-unqualified object type T
8069 // there exist candidate operator functions of the form
8070 //
8071 // T* operator+(T*, ptrdiff_t);
8072 // T& operator[](T*, ptrdiff_t); [BELOW]
8073 // T* operator-(T*, ptrdiff_t);
8074 // T* operator+(ptrdiff_t, T*);
8075 // T& operator[](ptrdiff_t, T*); [BELOW]
8076 //
8077 // C++ [over.built]p14:
8078 //
8079 // For every T, where T is a pointer to object type, there
8080 // exist candidate operator functions of the form
8081 //
8082 // ptrdiff_t operator-(T, T);
8083 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8084 /// Set of (canonical) types that we've already handled.
8085 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8086
8087 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00008088 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008089 S.Context.getPointerDiffType(),
8090 S.Context.getPointerDiffType(),
8091 };
8092 for (BuiltinCandidateTypeSet::iterator
8093 Ptr = CandidateTypes[Arg].pointer_begin(),
8094 PtrEnd = CandidateTypes[Arg].pointer_end();
8095 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00008096 QualType PointeeTy = (*Ptr)->getPointeeType();
8097 if (!PointeeTy->isObjectType())
8098 continue;
8099
Eric Christopher9207a522015-08-21 16:24:01 +00008100 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008101 if (Arg == 0 || Op == OO_Plus) {
8102 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8103 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00008104 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008105 }
8106 if (Op == OO_Minus) {
8107 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00008108 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008109 continue;
8110
8111 QualType ParamTypes[2] = { *Ptr, *Ptr };
8112 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00008113 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008114 }
8115 }
8116 }
8117 }
8118
8119 // C++ [over.built]p12:
8120 //
8121 // For every pair of promoted arithmetic types L and R, there
8122 // exist candidate operator functions of the form
8123 //
8124 // LR operator*(L, R);
8125 // LR operator/(L, R);
8126 // LR operator+(L, R);
8127 // LR operator-(L, R);
8128 // bool operator<(L, R);
8129 // bool operator>(L, R);
8130 // bool operator<=(L, R);
8131 // bool operator>=(L, R);
8132 // bool operator==(L, R);
8133 // bool operator!=(L, R);
8134 //
8135 // where LR is the result of the usual arithmetic conversions
8136 // between types L and R.
8137 //
8138 // C++ [over.built]p24:
8139 //
8140 // For every pair of promoted arithmetic types L and R, there exist
8141 // candidate operator functions of the form
8142 //
8143 // LR operator?(bool, L, R);
8144 //
8145 // where LR is the result of the usual arithmetic conversions
8146 // between types L and R.
8147 // Our candidates ignore the first parameter.
8148 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008149 if (!HasArithmeticOrEnumeralCandidateType)
8150 return;
8151
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008152 for (unsigned Left = FirstPromotedArithmeticType;
8153 Left < LastPromotedArithmeticType; ++Left) {
8154 for (unsigned Right = FirstPromotedArithmeticType;
8155 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00008156 QualType LandR[2] = { getArithmeticType(Left),
8157 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008158 QualType Result =
8159 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00008160 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00008161 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008162 }
8163 }
8164
8165 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8166 // conditional operator for vector types.
8167 for (BuiltinCandidateTypeSet::iterator
8168 Vec1 = CandidateTypes[0].vector_begin(),
8169 Vec1End = CandidateTypes[0].vector_end();
8170 Vec1 != Vec1End; ++Vec1) {
8171 for (BuiltinCandidateTypeSet::iterator
8172 Vec2 = CandidateTypes[1].vector_begin(),
8173 Vec2End = CandidateTypes[1].vector_end();
8174 Vec2 != Vec2End; ++Vec2) {
8175 QualType LandR[2] = { *Vec1, *Vec2 };
8176 QualType Result = S.Context.BoolTy;
8177 if (!isComparison) {
8178 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
8179 Result = *Vec1;
8180 else
8181 Result = *Vec2;
8182 }
8183
Richard Smithe54c3072013-05-05 15:51:06 +00008184 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008185 }
8186 }
8187 }
8188
8189 // C++ [over.built]p17:
8190 //
8191 // For every pair of promoted integral types L and R, there
8192 // exist candidate operator functions of the form
8193 //
8194 // LR operator%(L, R);
8195 // LR operator&(L, R);
8196 // LR operator^(L, R);
8197 // LR operator|(L, R);
8198 // L operator<<(L, R);
8199 // L operator>>(L, R);
8200 //
8201 // where LR is the result of the usual arithmetic conversions
8202 // between types L and R.
8203 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008204 if (!HasArithmeticOrEnumeralCandidateType)
8205 return;
8206
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008207 for (unsigned Left = FirstPromotedIntegralType;
8208 Left < LastPromotedIntegralType; ++Left) {
8209 for (unsigned Right = FirstPromotedIntegralType;
8210 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00008211 QualType LandR[2] = { getArithmeticType(Left),
8212 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008213 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
8214 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00008215 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00008216 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008217 }
8218 }
8219 }
8220
8221 // C++ [over.built]p20:
8222 //
8223 // For every pair (T, VQ), where T is an enumeration or
8224 // pointer to member type and VQ is either volatile or
8225 // empty, there exist candidate operator functions of the form
8226 //
8227 // VQ T& operator=(VQ T&, T);
8228 void addAssignmentMemberPointerOrEnumeralOverloads() {
8229 /// Set of (canonical) types that we've already handled.
8230 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8231
8232 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8233 for (BuiltinCandidateTypeSet::iterator
8234 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8235 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8236 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00008237 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008238 continue;
8239
Richard Smithe54c3072013-05-05 15:51:06 +00008240 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008241 }
8242
8243 for (BuiltinCandidateTypeSet::iterator
8244 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8245 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8246 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008247 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008248 continue;
8249
Richard Smithe54c3072013-05-05 15:51:06 +00008250 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008251 }
8252 }
8253 }
8254
8255 // C++ [over.built]p19:
8256 //
8257 // For every pair (T, VQ), where T is any type and VQ is either
8258 // volatile or empty, there exist candidate operator functions
8259 // of the form
8260 //
8261 // T*VQ& operator=(T*VQ&, T*);
8262 //
8263 // C++ [over.built]p21:
8264 //
8265 // For every pair (T, VQ), where T is a cv-qualified or
8266 // cv-unqualified object type and VQ is either volatile or
8267 // empty, there exist candidate operator functions of the form
8268 //
8269 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8270 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8271 void addAssignmentPointerOverloads(bool isEqualOp) {
8272 /// Set of (canonical) types that we've already handled.
8273 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8274
8275 for (BuiltinCandidateTypeSet::iterator
8276 Ptr = CandidateTypes[0].pointer_begin(),
8277 PtrEnd = CandidateTypes[0].pointer_end();
8278 Ptr != PtrEnd; ++Ptr) {
8279 // If this is operator=, keep track of the builtin candidates we added.
8280 if (isEqualOp)
8281 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008282 else if (!(*Ptr)->getPointeeType()->isObjectType())
8283 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008284
8285 // non-volatile version
8286 QualType ParamTypes[2] = {
8287 S.Context.getLValueReferenceType(*Ptr),
8288 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8289 };
Richard Smithe54c3072013-05-05 15:51:06 +00008290 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008291 /*IsAssigmentOperator=*/ isEqualOp);
8292
Douglas Gregor5bee2582012-06-04 00:15:09 +00008293 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8294 VisibleTypeConversionsQuals.hasVolatile();
8295 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008296 // volatile version
8297 ParamTypes[0] =
8298 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008299 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008300 /*IsAssigmentOperator=*/isEqualOp);
8301 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008302
8303 if (!(*Ptr).isRestrictQualified() &&
8304 VisibleTypeConversionsQuals.hasRestrict()) {
8305 // restrict version
8306 ParamTypes[0]
8307 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008309 /*IsAssigmentOperator=*/isEqualOp);
8310
8311 if (NeedVolatile) {
8312 // volatile restrict version
8313 ParamTypes[0]
8314 = S.Context.getLValueReferenceType(
8315 S.Context.getCVRQualifiedType(*Ptr,
8316 (Qualifiers::Volatile |
8317 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008318 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008319 /*IsAssigmentOperator=*/isEqualOp);
8320 }
8321 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008322 }
8323
8324 if (isEqualOp) {
8325 for (BuiltinCandidateTypeSet::iterator
8326 Ptr = CandidateTypes[1].pointer_begin(),
8327 PtrEnd = CandidateTypes[1].pointer_end();
8328 Ptr != PtrEnd; ++Ptr) {
8329 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008330 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008331 continue;
8332
Chandler Carruth8e543b32010-12-12 08:17:55 +00008333 QualType ParamTypes[2] = {
8334 S.Context.getLValueReferenceType(*Ptr),
8335 *Ptr,
8336 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008337
8338 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00008339 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008340 /*IsAssigmentOperator=*/true);
8341
Douglas Gregor5bee2582012-06-04 00:15:09 +00008342 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8343 VisibleTypeConversionsQuals.hasVolatile();
8344 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008345 // volatile version
8346 ParamTypes[0] =
8347 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008348 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8349 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008350 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008351
8352 if (!(*Ptr).isRestrictQualified() &&
8353 VisibleTypeConversionsQuals.hasRestrict()) {
8354 // restrict version
8355 ParamTypes[0]
8356 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008357 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8358 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008359
8360 if (NeedVolatile) {
8361 // volatile restrict version
8362 ParamTypes[0]
8363 = S.Context.getLValueReferenceType(
8364 S.Context.getCVRQualifiedType(*Ptr,
8365 (Qualifiers::Volatile |
8366 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008367 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8368 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008369 }
8370 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008371 }
8372 }
8373 }
8374
8375 // C++ [over.built]p18:
8376 //
8377 // For every triple (L, VQ, R), where L is an arithmetic type,
8378 // VQ is either volatile or empty, and R is a promoted
8379 // arithmetic type, there exist candidate operator functions of
8380 // the form
8381 //
8382 // VQ L& operator=(VQ L&, R);
8383 // VQ L& operator*=(VQ L&, R);
8384 // VQ L& operator/=(VQ L&, R);
8385 // VQ L& operator+=(VQ L&, R);
8386 // VQ L& operator-=(VQ L&, R);
8387 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008388 if (!HasArithmeticOrEnumeralCandidateType)
8389 return;
8390
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008391 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8392 for (unsigned Right = FirstPromotedArithmeticType;
8393 Right < LastPromotedArithmeticType; ++Right) {
8394 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008395 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008396
8397 // Add this built-in operator as a candidate (VQ is empty).
8398 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008399 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008400 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008401 /*IsAssigmentOperator=*/isEqualOp);
8402
8403 // Add this built-in operator as a candidate (VQ is 'volatile').
8404 if (VisibleTypeConversionsQuals.hasVolatile()) {
8405 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008406 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008407 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008408 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008409 /*IsAssigmentOperator=*/isEqualOp);
8410 }
8411 }
8412 }
8413
8414 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8415 for (BuiltinCandidateTypeSet::iterator
8416 Vec1 = CandidateTypes[0].vector_begin(),
8417 Vec1End = CandidateTypes[0].vector_end();
8418 Vec1 != Vec1End; ++Vec1) {
8419 for (BuiltinCandidateTypeSet::iterator
8420 Vec2 = CandidateTypes[1].vector_begin(),
8421 Vec2End = CandidateTypes[1].vector_end();
8422 Vec2 != Vec2End; ++Vec2) {
8423 QualType ParamTypes[2];
8424 ParamTypes[1] = *Vec2;
8425 // Add this built-in operator as a candidate (VQ is empty).
8426 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008427 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008428 /*IsAssigmentOperator=*/isEqualOp);
8429
8430 // Add this built-in operator as a candidate (VQ is 'volatile').
8431 if (VisibleTypeConversionsQuals.hasVolatile()) {
8432 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8433 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008434 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008435 /*IsAssigmentOperator=*/isEqualOp);
8436 }
8437 }
8438 }
8439 }
8440
8441 // C++ [over.built]p22:
8442 //
8443 // For every triple (L, VQ, R), where L is an integral type, VQ
8444 // is either volatile or empty, and R is a promoted integral
8445 // type, there exist candidate operator functions of the form
8446 //
8447 // VQ L& operator%=(VQ L&, R);
8448 // VQ L& operator<<=(VQ L&, R);
8449 // VQ L& operator>>=(VQ L&, R);
8450 // VQ L& operator&=(VQ L&, R);
8451 // VQ L& operator^=(VQ L&, R);
8452 // VQ L& operator|=(VQ L&, R);
8453 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008454 if (!HasArithmeticOrEnumeralCandidateType)
8455 return;
8456
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008457 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8458 for (unsigned Right = FirstPromotedIntegralType;
8459 Right < LastPromotedIntegralType; ++Right) {
8460 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008461 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008462
8463 // Add this built-in operator as a candidate (VQ is empty).
8464 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008465 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008466 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008467 if (VisibleTypeConversionsQuals.hasVolatile()) {
8468 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008469 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008470 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8471 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008472 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008473 }
8474 }
8475 }
8476 }
8477
8478 // C++ [over.operator]p23:
8479 //
8480 // There also exist candidate operator functions of the form
8481 //
8482 // bool operator!(bool);
8483 // bool operator&&(bool, bool);
8484 // bool operator||(bool, bool);
8485 void addExclaimOverload() {
8486 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008487 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008488 /*IsAssignmentOperator=*/false,
8489 /*NumContextualBoolArguments=*/1);
8490 }
8491 void addAmpAmpOrPipePipeOverload() {
8492 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008493 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008494 /*IsAssignmentOperator=*/false,
8495 /*NumContextualBoolArguments=*/2);
8496 }
8497
8498 // C++ [over.built]p13:
8499 //
8500 // For every cv-qualified or cv-unqualified object type T there
8501 // exist candidate operator functions of the form
8502 //
8503 // T* operator+(T*, ptrdiff_t); [ABOVE]
8504 // T& operator[](T*, ptrdiff_t);
8505 // T* operator-(T*, ptrdiff_t); [ABOVE]
8506 // T* operator+(ptrdiff_t, T*); [ABOVE]
8507 // T& operator[](ptrdiff_t, T*);
8508 void addSubscriptOverloads() {
8509 for (BuiltinCandidateTypeSet::iterator
8510 Ptr = CandidateTypes[0].pointer_begin(),
8511 PtrEnd = CandidateTypes[0].pointer_end();
8512 Ptr != PtrEnd; ++Ptr) {
8513 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8514 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008515 if (!PointeeType->isObjectType())
8516 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008517
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008518 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8519
8520 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008521 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008522 }
8523
8524 for (BuiltinCandidateTypeSet::iterator
8525 Ptr = CandidateTypes[1].pointer_begin(),
8526 PtrEnd = CandidateTypes[1].pointer_end();
8527 Ptr != PtrEnd; ++Ptr) {
8528 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8529 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008530 if (!PointeeType->isObjectType())
8531 continue;
8532
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008533 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8534
8535 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008536 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008537 }
8538 }
8539
8540 // C++ [over.built]p11:
8541 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8542 // C1 is the same type as C2 or is a derived class of C2, T is an object
8543 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8544 // there exist candidate operator functions of the form
8545 //
8546 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8547 //
8548 // where CV12 is the union of CV1 and CV2.
8549 void addArrowStarOverloads() {
8550 for (BuiltinCandidateTypeSet::iterator
8551 Ptr = CandidateTypes[0].pointer_begin(),
8552 PtrEnd = CandidateTypes[0].pointer_end();
8553 Ptr != PtrEnd; ++Ptr) {
8554 QualType C1Ty = (*Ptr);
8555 QualType C1;
8556 QualifierCollector Q1;
8557 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8558 if (!isa<RecordType>(C1))
8559 continue;
8560 // heuristic to reduce number of builtin candidates in the set.
8561 // Add volatile/restrict version only if there are conversions to a
8562 // volatile/restrict type.
8563 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8564 continue;
8565 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8566 continue;
8567 for (BuiltinCandidateTypeSet::iterator
8568 MemPtr = CandidateTypes[1].member_pointer_begin(),
8569 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8570 MemPtr != MemPtrEnd; ++MemPtr) {
8571 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8572 QualType C2 = QualType(mptr->getClass(), 0);
8573 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008574 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008575 break;
8576 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8577 // build CV12 T&
8578 QualType T = mptr->getPointeeType();
8579 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8580 T.isVolatileQualified())
8581 continue;
8582 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8583 T.isRestrictQualified())
8584 continue;
8585 T = Q1.apply(S.Context, T);
8586 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008587 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008588 }
8589 }
8590 }
8591
8592 // Note that we don't consider the first argument, since it has been
8593 // contextually converted to bool long ago. The candidates below are
8594 // therefore added as binary.
8595 //
8596 // C++ [over.built]p25:
8597 // For every type T, where T is a pointer, pointer-to-member, or scoped
8598 // enumeration type, there exist candidate operator functions of the form
8599 //
8600 // T operator?(bool, T, T);
8601 //
8602 void addConditionalOperatorOverloads() {
8603 /// Set of (canonical) types that we've already handled.
8604 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8605
8606 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8607 for (BuiltinCandidateTypeSet::iterator
8608 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8609 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8610 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008611 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008612 continue;
8613
8614 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008615 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008616 }
8617
8618 for (BuiltinCandidateTypeSet::iterator
8619 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8620 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8621 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008622 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008623 continue;
8624
8625 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008626 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008627 }
8628
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008629 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008630 for (BuiltinCandidateTypeSet::iterator
8631 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8632 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8633 Enum != EnumEnd; ++Enum) {
8634 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8635 continue;
8636
David Blaikie82e95a32014-11-19 07:49:47 +00008637 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008638 continue;
8639
8640 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008641 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008642 }
8643 }
8644 }
8645 }
8646};
8647
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008648} // end anonymous namespace
8649
8650/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8651/// operator overloads to the candidate set (C++ [over.built]), based
8652/// on the operator @p Op and the arguments given. For example, if the
8653/// operator is a binary '+', this routine might add "int
8654/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008655void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8656 SourceLocation OpLoc,
8657 ArrayRef<Expr *> Args,
8658 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008659 // Find all of the types that the arguments can convert to, but only
8660 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008661 // that make use of these types. Also record whether we encounter non-record
8662 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008663 Qualifiers VisibleTypeConversionsQuals;
8664 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008665 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008666 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008667
8668 bool HasNonRecordCandidateType = false;
8669 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008670 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008671 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008672 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008673 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8674 OpLoc,
8675 true,
8676 (Op == OO_Exclaim ||
8677 Op == OO_AmpAmp ||
8678 Op == OO_PipePipe),
8679 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008680 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8681 CandidateTypes[ArgIdx].hasNonRecordTypes();
8682 HasArithmeticOrEnumeralCandidateType =
8683 HasArithmeticOrEnumeralCandidateType ||
8684 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008685 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008686
Chandler Carruth00a38332010-12-13 01:44:01 +00008687 // Exit early when no non-record types have been added to the candidate set
8688 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008689 //
8690 // We can't exit early for !, ||, or &&, since there we have always have
8691 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008692 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008693 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008694 return;
8695
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008696 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008697 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008698 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008699 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008700 CandidateTypes, CandidateSet);
8701
8702 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008703 switch (Op) {
8704 case OO_None:
8705 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008706 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008707
Chandler Carruth5184de02010-12-12 08:51:33 +00008708 case OO_New:
8709 case OO_Delete:
8710 case OO_Array_New:
8711 case OO_Array_Delete:
8712 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008713 llvm_unreachable(
8714 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008715
8716 case OO_Comma:
8717 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008718 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008719 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008720 // -- For the operator ',', the unary operator '&', the
8721 // operator '->', or the operator 'co_await', the
8722 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008723 break;
8724
8725 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008726 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008727 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008728 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008729
8730 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008731 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008732 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008733 } else {
8734 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8735 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8736 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008737 break;
8738
Chandler Carruth5184de02010-12-12 08:51:33 +00008739 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008740 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008741 OpBuilder.addUnaryStarPointerOverloads();
8742 else
8743 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8744 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008745
Chandler Carruth5184de02010-12-12 08:51:33 +00008746 case OO_Slash:
8747 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008748 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008749
8750 case OO_PlusPlus:
8751 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008752 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8753 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008754 break;
8755
Douglas Gregor84605ae2009-08-24 13:43:27 +00008756 case OO_EqualEqual:
8757 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008758 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008759 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008760
Douglas Gregora11693b2008-11-12 17:17:38 +00008761 case OO_Less:
8762 case OO_Greater:
8763 case OO_LessEqual:
8764 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008765 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008766 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8767 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008768
Douglas Gregora11693b2008-11-12 17:17:38 +00008769 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008770 case OO_Caret:
8771 case OO_Pipe:
8772 case OO_LessLess:
8773 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008774 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008775 break;
8776
Chandler Carruth5184de02010-12-12 08:51:33 +00008777 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008778 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008779 // C++ [over.match.oper]p3:
8780 // -- For the operator ',', the unary operator '&', or the
8781 // operator '->', the built-in candidates set is empty.
8782 break;
8783
8784 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8785 break;
8786
8787 case OO_Tilde:
8788 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8789 break;
8790
Douglas Gregora11693b2008-11-12 17:17:38 +00008791 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008792 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008793 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008794
8795 case OO_PlusEqual:
8796 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008797 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008798 // Fall through.
8799
8800 case OO_StarEqual:
8801 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008802 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008803 break;
8804
8805 case OO_PercentEqual:
8806 case OO_LessLessEqual:
8807 case OO_GreaterGreaterEqual:
8808 case OO_AmpEqual:
8809 case OO_CaretEqual:
8810 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008811 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008812 break;
8813
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008814 case OO_Exclaim:
8815 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008816 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008817
Douglas Gregora11693b2008-11-12 17:17:38 +00008818 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008819 case OO_PipePipe:
8820 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008821 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008822
8823 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008824 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008825 break;
8826
8827 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008828 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008829 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008830
8831 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008832 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008833 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8834 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008835 }
8836}
8837
Douglas Gregore254f902009-02-04 00:32:51 +00008838/// \brief Add function candidates found via argument-dependent lookup
8839/// to the set of overloading candidates.
8840///
8841/// This routine performs argument-dependent name lookup based on the
8842/// given function name (which may also be an operator name) and adds
8843/// all of the overload candidates found by ADL to the overload
8844/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008845void
Douglas Gregore254f902009-02-04 00:32:51 +00008846Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008847 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008848 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008849 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008850 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008851 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008852 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008853
John McCall91f61fc2010-01-26 06:04:06 +00008854 // FIXME: This approach for uniquing ADL results (and removing
8855 // redundant candidates from the set) relies on pointer-equality,
8856 // which means we need to key off the canonical decl. However,
8857 // always going back to the canonical decl might not get us the
8858 // right set of default arguments. What default arguments are
8859 // we supposed to consider on ADL candidates, anyway?
8860
Douglas Gregorcabea402009-09-22 15:41:20 +00008861 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008862 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008863
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008864 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008865 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8866 CandEnd = CandidateSet.end();
8867 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008868 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008869 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008870 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008871 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008872 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008873
8874 // For each of the ADL candidates we found, add it to the overload
8875 // set.
John McCall8fe68082010-01-26 07:16:45 +00008876 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008877 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008878 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008879 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008880 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008881
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008882 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8883 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008884 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008885 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008886 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008887 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008888 }
Douglas Gregore254f902009-02-04 00:32:51 +00008889}
8890
George Burgess IV3dc166912016-05-10 01:59:34 +00008891namespace {
8892enum class Comparison { Equal, Better, Worse };
8893}
8894
8895/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8896/// overload resolution.
8897///
8898/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8899/// Cand1's first N enable_if attributes have precisely the same conditions as
8900/// Cand2's first N enable_if attributes (where N = the number of enable_if
8901/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8902///
8903/// Note that you can have a pair of candidates such that Cand1's enable_if
8904/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8905/// worse than Cand1's.
8906static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8907 const FunctionDecl *Cand2) {
8908 // Common case: One (or both) decls don't have enable_if attrs.
8909 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8910 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8911 if (!Cand1Attr || !Cand2Attr) {
8912 if (Cand1Attr == Cand2Attr)
8913 return Comparison::Equal;
8914 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8915 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008916
8917 // FIXME: The next several lines are just
8918 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8919 // instead of reverse order which is how they're stored in the AST.
8920 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8921 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8922
George Burgess IV3dc166912016-05-10 01:59:34 +00008923 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8924 // has fewer enable_if attributes than Cand2.
8925 if (Cand1Attrs.size() < Cand2Attrs.size())
8926 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008927
8928 auto Cand1I = Cand1Attrs.begin();
8929 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8930 for (auto &Cand2A : Cand2Attrs) {
8931 Cand1ID.clear();
8932 Cand2ID.clear();
8933
8934 auto &Cand1A = *Cand1I++;
8935 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8936 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8937 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008938 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008939 }
8940
George Burgess IV3dc166912016-05-10 01:59:34 +00008941 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008942}
8943
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008944/// isBetterOverloadCandidate - Determines whether the first overload
8945/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008946bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8947 const OverloadCandidate &Cand2,
8948 SourceLocation Loc,
8949 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008950 // Define viable functions to be better candidates than non-viable
8951 // functions.
8952 if (!Cand2.Viable)
8953 return Cand1.Viable;
8954 else if (!Cand1.Viable)
8955 return false;
8956
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008957 // C++ [over.match.best]p1:
8958 //
8959 // -- if F is a static member function, ICS1(F) is defined such
8960 // that ICS1(F) is neither better nor worse than ICS1(G) for
8961 // any function G, and, symmetrically, ICS1(G) is neither
8962 // better nor worse than ICS1(F).
8963 unsigned StartArg = 0;
8964 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8965 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008966
George Burgess IVfbad5b22016-09-07 20:03:19 +00008967 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8968 // We don't allow incompatible pointer conversions in C++.
8969 if (!S.getLangOpts().CPlusPlus)
8970 return ICS.isStandard() &&
8971 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8972
8973 // The only ill-formed conversion we allow in C++ is the string literal to
8974 // char* conversion, which is only considered ill-formed after C++11.
8975 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8976 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8977 };
8978
8979 // Define functions that don't require ill-formed conversions for a given
8980 // argument to be better candidates than functions that do.
Richard Smith6eedfe72017-01-09 08:01:21 +00008981 unsigned NumArgs = Cand1.Conversions.size();
8982 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
George Burgess IVfbad5b22016-09-07 20:03:19 +00008983 bool HasBetterConversion = false;
8984 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8985 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8986 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8987 if (Cand1Bad != Cand2Bad) {
8988 if (Cand1Bad)
8989 return false;
8990 HasBetterConversion = true;
8991 }
8992 }
8993
8994 if (HasBetterConversion)
8995 return true;
8996
Douglas Gregord3cb3562009-07-07 23:38:56 +00008997 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008998 // A viable function F1 is defined to be a better function than another
8999 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00009000 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009001 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00009002 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00009003 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009004 Cand2.Conversions[ArgIdx])) {
9005 case ImplicitConversionSequence::Better:
9006 // Cand1 has a better conversion sequence.
9007 HasBetterConversion = true;
9008 break;
9009
9010 case ImplicitConversionSequence::Worse:
9011 // Cand1 can't be better than Cand2.
9012 return false;
9013
9014 case ImplicitConversionSequence::Indistinguishable:
9015 // Do nothing.
9016 break;
9017 }
9018 }
9019
Mike Stump11289f42009-09-09 15:08:12 +00009020 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00009021 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009022 if (HasBetterConversion)
9023 return true;
9024
Douglas Gregora1f013e2008-11-07 22:36:19 +00009025 // -- the context is an initialization by user-defined conversion
9026 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9027 // from the return type of F1 to the destination type (i.e.,
9028 // the type of the entity being initialized) is a better
9029 // conversion sequence than the standard conversion sequence
9030 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00009031 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00009032 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00009033 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00009034 // First check whether we prefer one of the conversion functions over the
9035 // other. This only distinguishes the results in non-standard, extension
9036 // cases such as the conversion from a lambda closure type to a function
9037 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00009038 ImplicitConversionSequence::CompareKind Result =
9039 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9040 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00009041 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00009042 Cand1.FinalConversion,
9043 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00009044
Richard Smithec2748a2014-05-17 04:36:39 +00009045 if (Result != ImplicitConversionSequence::Indistinguishable)
9046 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00009047
9048 // FIXME: Compare kind of reference binding if conversion functions
9049 // convert to a reference type used in direct reference binding, per
9050 // C++14 [over.match.best]p1 section 2 bullet 3.
9051 }
9052
9053 // -- F1 is a non-template function and F2 is a function template
9054 // specialization, or, if not that,
9055 bool Cand1IsSpecialization = Cand1.Function &&
9056 Cand1.Function->getPrimaryTemplate();
9057 bool Cand2IsSpecialization = Cand2.Function &&
9058 Cand2.Function->getPrimaryTemplate();
9059 if (Cand1IsSpecialization != Cand2IsSpecialization)
9060 return Cand2IsSpecialization;
9061
9062 // -- F1 and F2 are function template specializations, and the function
9063 // template for F1 is more specialized than the template for F2
9064 // according to the partial ordering rules described in 14.5.5.2, or,
9065 // if not that,
9066 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9067 if (FunctionTemplateDecl *BetterTemplate
9068 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9069 Cand2.Function->getPrimaryTemplate(),
9070 Loc,
9071 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9072 : TPOC_Call,
9073 Cand1.ExplicitCallArguments,
9074 Cand2.ExplicitCallArguments))
9075 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00009076 }
9077
Richard Smith5179eb72016-06-28 19:03:57 +00009078 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9079 // A derived-class constructor beats an (inherited) base class constructor.
9080 bool Cand1IsInherited =
9081 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9082 bool Cand2IsInherited =
9083 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9084 if (Cand1IsInherited != Cand2IsInherited)
9085 return Cand2IsInherited;
9086 else if (Cand1IsInherited) {
9087 assert(Cand2IsInherited);
9088 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9089 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9090 if (Cand1Class->isDerivedFrom(Cand2Class))
9091 return true;
9092 if (Cand2Class->isDerivedFrom(Cand1Class))
9093 return false;
9094 // Inherited from sibling base classes: still ambiguous.
9095 }
9096
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009097 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00009098 if (Cand1.Function && Cand2.Function) {
9099 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9100 if (Cmp != Comparison::Equal)
9101 return Cmp == Comparison::Better;
9102 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009103
Justin Lebar25c4a812016-03-29 16:24:16 +00009104 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00009105 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9106 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9107 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9108 }
9109
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009110 bool HasPS1 = Cand1.Function != nullptr &&
9111 functionHasPassObjectSizeParams(Cand1.Function);
9112 bool HasPS2 = Cand2.Function != nullptr &&
9113 functionHasPassObjectSizeParams(Cand2.Function);
9114 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009115}
9116
Richard Smith2dbe4042015-11-04 19:26:32 +00009117/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00009118/// name lookup and overload resolution. This applies when the same internal/no
9119/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00009120/// the same header). In such a case, we don't consider the declarations to
9121/// declare the same entity, but we also don't want lookups with both
9122/// declarations visible to be ambiguous in some cases (this happens when using
9123/// a modularized libstdc++).
9124bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9125 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00009126 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9127 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9128 if (!VA || !VB)
9129 return false;
9130
9131 // The declarations must be declaring the same name as an internal linkage
9132 // entity in different modules.
9133 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9134 VB->getDeclContext()->getRedeclContext()) ||
9135 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9136 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9137 VA->isExternallyVisible() || VB->isExternallyVisible())
9138 return false;
9139
9140 // Check that the declarations appear to be equivalent.
9141 //
9142 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9143 // For constants and functions, we should check the initializer or body is
9144 // the same. For non-constant variables, we shouldn't allow it at all.
9145 if (Context.hasSameType(VA->getType(), VB->getType()))
9146 return true;
9147
9148 // Enum constants within unnamed enumerations will have different types, but
9149 // may still be similar enough to be interchangeable for our purposes.
9150 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9151 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9152 // Only handle anonymous enums. If the enumerations were named and
9153 // equivalent, they would have been merged to the same type.
9154 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9155 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9156 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9157 !Context.hasSameType(EnumA->getIntegerType(),
9158 EnumB->getIntegerType()))
9159 return false;
9160 // Allow this only if the value is the same for both enumerators.
9161 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9162 }
9163 }
9164
9165 // Nothing else is sufficiently similar.
9166 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00009167}
9168
9169void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9170 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9171 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9172
9173 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9174 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9175 << !M << (M ? M->getFullModuleName() : "");
9176
9177 for (auto *E : Equiv) {
9178 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9179 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9180 << !M << (M ? M->getFullModuleName() : "");
9181 }
Richard Smith896c66e2015-10-21 07:13:52 +00009182}
9183
George Burgess IV177399e2017-01-09 04:12:14 +00009184static bool isCandidateUnavailableDueToDiagnoseIf(const OverloadCandidate &OC) {
9185 ArrayRef<DiagnoseIfAttr *> Info = OC.getDiagnoseIfInfo();
9186 if (!Info.empty() && Info[0]->isError())
9187 return true;
9188
9189 assert(llvm::all_of(Info,
9190 [](const DiagnoseIfAttr *A) { return !A->isError(); }) &&
9191 "DiagnoseIf info shouldn't have mixed warnings and errors.");
9192 return false;
9193}
9194
Mike Stump11289f42009-09-09 15:08:12 +00009195/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009196/// within an overload candidate set.
9197///
James Dennettffad8b72012-06-22 08:10:18 +00009198/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009199/// which overload resolution occurs.
9200///
James Dennettffad8b72012-06-22 08:10:18 +00009201/// \param Best If overload resolution was successful or found a deleted
9202/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009203///
9204/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00009205OverloadingResult
9206OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00009207 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00009208 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00009209 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9210 std::transform(begin(), end(), std::back_inserter(Candidates),
9211 [](OverloadCandidate &Cand) { return &Cand; });
9212
Justin Lebar66a2ab92016-08-10 00:40:43 +00009213 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9214 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00009215 // compilation mode only one call variant is viable. We need to
9216 // exclude non-viable overload candidates from consideration based
9217 // only on their host/device attributes. Specifically, if one
9218 // candidate call is WrongSide and the other is SameSide, we ignore
9219 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00009220 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00009221 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9222 bool ContainsSameSideCandidate =
9223 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9224 return Cand->Function &&
9225 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9226 Sema::CFP_SameSide;
9227 });
9228 if (ContainsSameSideCandidate) {
9229 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9230 return Cand->Function &&
9231 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9232 Sema::CFP_WrongSide;
9233 };
George Burgess IV8684b032017-01-04 19:16:29 +00009234 llvm::erase_if(Candidates, IsWrongSideCandidate);
Artem Belevich18609102016-02-12 18:29:18 +00009235 }
9236 }
9237
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009238 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00009239 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00009240 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00009241 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009242 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00009243 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009244 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009245
9246 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00009247 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009248 return OR_No_Viable_Function;
9249
Richard Smith2dbe4042015-11-04 19:26:32 +00009250 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00009251
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009252 // Make sure that this function is better than every other viable
9253 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00009254 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00009255 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009256 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009257 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00009258 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00009259 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9260 Cand->Function)) {
9261 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00009262 continue;
9263 }
9264
John McCall5c32be02010-08-24 20:38:10 +00009265 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009266 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00009267 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009268 }
Mike Stump11289f42009-09-09 15:08:12 +00009269
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009270 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00009271 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009272 (Best->Function->isDeleted() ||
George Burgess IV177399e2017-01-09 04:12:14 +00009273 S.isFunctionConsideredUnavailable(Best->Function) ||
9274 isCandidateUnavailableDueToDiagnoseIf(*Best)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00009275 return OR_Deleted;
9276
Richard Smith2dbe4042015-11-04 19:26:32 +00009277 if (!EquivalentCands.empty())
9278 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9279 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00009280
George Burgess IV177399e2017-01-09 04:12:14 +00009281 for (const auto *W : Best->getDiagnoseIfInfo()) {
9282 assert(W->isWarning() && "Errors should've been caught earlier!");
9283 S.emitDiagnoseIfDiagnostic(Loc, W);
9284 }
9285
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009286 return OR_Success;
9287}
9288
John McCall53262c92010-01-12 02:15:36 +00009289namespace {
9290
9291enum OverloadCandidateKind {
9292 oc_function,
9293 oc_method,
9294 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00009295 oc_function_template,
9296 oc_method_template,
9297 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00009298 oc_implicit_default_constructor,
9299 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009300 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009301 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009302 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00009303 oc_inherited_constructor,
9304 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00009305};
9306
George Burgess IVd66d37c2016-10-28 21:42:06 +00009307static OverloadCandidateKind
9308ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9309 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009310 bool isTemplate = false;
9311
9312 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9313 isTemplate = true;
9314 Description = S.getTemplateArgumentBindingsText(
9315 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9316 }
John McCallfd0b2f82010-01-06 09:43:14 +00009317
9318 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00009319 if (!Ctor->isImplicit()) {
9320 if (isa<ConstructorUsingShadowDecl>(Found))
9321 return isTemplate ? oc_inherited_constructor_template
9322 : oc_inherited_constructor;
9323 else
9324 return isTemplate ? oc_constructor_template : oc_constructor;
9325 }
Sebastian Redl08905022011-02-05 19:23:19 +00009326
Alexis Hunt119c10e2011-05-25 23:16:36 +00009327 if (Ctor->isDefaultConstructor())
9328 return oc_implicit_default_constructor;
9329
9330 if (Ctor->isMoveConstructor())
9331 return oc_implicit_move_constructor;
9332
9333 assert(Ctor->isCopyConstructor() &&
9334 "unexpected sort of implicit constructor");
9335 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00009336 }
9337
9338 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9339 // This actually gets spelled 'candidate function' for now, but
9340 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00009341 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00009342 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00009343
Alexis Hunt119c10e2011-05-25 23:16:36 +00009344 if (Meth->isMoveAssignmentOperator())
9345 return oc_implicit_move_assignment;
9346
Douglas Gregor12695102012-02-10 08:36:38 +00009347 if (Meth->isCopyAssignmentOperator())
9348 return oc_implicit_copy_assignment;
9349
9350 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9351 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00009352 }
9353
John McCalle1ac8d12010-01-13 00:25:19 +00009354 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00009355}
9356
Richard Smith5179eb72016-06-28 19:03:57 +00009357void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9358 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9359 // set.
9360 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9361 S.Diag(FoundDecl->getLocation(),
9362 diag::note_ovl_candidate_inherited_constructor)
9363 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009364}
9365
John McCall53262c92010-01-12 02:15:36 +00009366} // end anonymous namespace
9367
George Burgess IV5f21c712015-10-12 19:57:04 +00009368static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9369 const FunctionDecl *FD) {
9370 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9371 bool AlwaysTrue;
9372 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9373 return false;
9374 if (!AlwaysTrue)
9375 return false;
9376 }
9377 return true;
9378}
9379
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009380/// \brief Returns true if we can take the address of the function.
9381///
9382/// \param Complain - If true, we'll emit a diagnostic
9383/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9384/// we in overload resolution?
9385/// \param Loc - The location of the statement we're complaining about. Ignored
9386/// if we're not complaining, or if we're in overload resolution.
9387static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9388 bool Complain,
9389 bool InOverloadResolution,
9390 SourceLocation Loc) {
9391 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9392 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009393 if (InOverloadResolution)
9394 S.Diag(FD->getLocStart(),
9395 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9396 else
9397 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9398 }
9399 return false;
9400 }
9401
George Burgess IV21081362016-07-24 23:12:40 +00009402 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9403 return P->hasAttr<PassObjectSizeAttr>();
9404 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009405 if (I == FD->param_end())
9406 return true;
9407
9408 if (Complain) {
9409 // Add one to ParamNo because it's user-facing
9410 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9411 if (InOverloadResolution)
9412 S.Diag(FD->getLocation(),
9413 diag::note_ovl_candidate_has_pass_object_size_params)
9414 << ParamNo;
9415 else
9416 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9417 << FD << ParamNo;
9418 }
9419 return false;
9420}
9421
9422static bool checkAddressOfCandidateIsAvailable(Sema &S,
9423 const FunctionDecl *FD) {
9424 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9425 /*InOverloadResolution=*/true,
9426 /*Loc=*/SourceLocation());
9427}
9428
9429bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9430 bool Complain,
9431 SourceLocation Loc) {
9432 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9433 /*InOverloadResolution=*/false,
9434 Loc);
9435}
9436
John McCall53262c92010-01-12 02:15:36 +00009437// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009438void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9439 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009440 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9441 return;
9442
John McCalle1ac8d12010-01-13 00:25:19 +00009443 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009444 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009445 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00009446 << (unsigned) K << Fn << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009447
9448 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009449 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009450 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009451}
9452
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009453// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009454// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009455void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9456 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009457 assert(OverloadedExpr->getType() == Context.OverloadTy);
9458
9459 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9460 OverloadExpr *OvlExpr = Ovl.Expression;
9461
9462 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9463 IEnd = OvlExpr->decls_end();
9464 I != IEnd; ++I) {
9465 if (FunctionTemplateDecl *FunTmpl =
9466 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009467 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009468 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009469 } else if (FunctionDecl *Fun
9470 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009471 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009472 }
9473 }
9474}
9475
John McCall0d1da222010-01-12 00:44:57 +00009476/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9477/// "lead" diagnostic; it will be given two arguments, the source and
9478/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009479void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9480 Sema &S,
9481 SourceLocation CaretLoc,
9482 const PartialDiagnostic &PDiag) const {
9483 S.Diag(CaretLoc, PDiag)
9484 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009485 // FIXME: The note limiting machinery is borrowed from
9486 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9487 // refactoring here.
9488 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9489 unsigned CandsShown = 0;
9490 AmbiguousConversionSequence::const_iterator I, E;
9491 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9492 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9493 break;
9494 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009495 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009496 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009497 if (I != E)
9498 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009499}
9500
Richard Smith17c00b42014-11-12 01:24:00 +00009501static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009502 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009503 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9504 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009505 assert(Cand->Function && "for now, candidate must be a function");
9506 FunctionDecl *Fn = Cand->Function;
9507
9508 // There's a conversion slot for the object argument if this is a
9509 // non-constructor method. Note that 'I' corresponds the
9510 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009511 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009512 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009513 if (I == 0)
9514 isObjectArgument = true;
9515 else
9516 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009517 }
9518
John McCalle1ac8d12010-01-13 00:25:19 +00009519 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009520 OverloadCandidateKind FnKind =
9521 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009522
John McCall6a61b522010-01-13 09:16:55 +00009523 Expr *FromExpr = Conv.Bad.FromExpr;
9524 QualType FromTy = Conv.Bad.getFromType();
9525 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009526
John McCallfb7ad0f2010-02-02 02:42:52 +00009527 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009528 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009529 Expr *E = FromExpr->IgnoreParens();
9530 if (isa<UnaryOperator>(E))
9531 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009532 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009533
9534 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9535 << (unsigned) FnKind << FnDesc
9536 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9537 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009538 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009539 return;
9540 }
9541
John McCall6d174642010-01-23 08:10:49 +00009542 // Do some hand-waving analysis to see if the non-viability is due
9543 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009544 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9545 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9546 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9547 CToTy = RT->getPointeeType();
9548 else {
9549 // TODO: detect and diagnose the full richness of const mismatches.
9550 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009551 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9552 CFromTy = FromPT->getPointeeType();
9553 CToTy = ToPT->getPointeeType();
9554 }
John McCall47000992010-01-14 03:28:57 +00009555 }
9556
9557 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9558 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009559 Qualifiers FromQs = CFromTy.getQualifiers();
9560 Qualifiers ToQs = CToTy.getQualifiers();
9561
9562 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9563 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9564 << (unsigned) FnKind << FnDesc
9565 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9566 << FromTy
9567 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9568 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009569 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009570 return;
9571 }
9572
John McCall31168b02011-06-15 23:02:42 +00009573 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009574 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009575 << (unsigned) FnKind << FnDesc
9576 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9577 << FromTy
9578 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9579 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009580 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009581 return;
9582 }
9583
Douglas Gregoraec25842011-04-26 23:16:46 +00009584 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9585 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9586 << (unsigned) FnKind << FnDesc
9587 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9588 << FromTy
9589 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9590 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009591 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009592 return;
9593 }
9594
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009595 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9596 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9597 << (unsigned) FnKind << FnDesc
9598 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9599 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009600 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009601 return;
9602 }
9603
John McCall47000992010-01-14 03:28:57 +00009604 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9605 assert(CVR && "unexpected qualifiers mismatch");
9606
9607 if (isObjectArgument) {
9608 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9609 << (unsigned) FnKind << FnDesc
9610 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9611 << FromTy << (CVR - 1);
9612 } else {
9613 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9614 << (unsigned) FnKind << FnDesc
9615 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9616 << FromTy << (CVR - 1) << I+1;
9617 }
Richard Smith5179eb72016-06-28 19:03:57 +00009618 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009619 return;
9620 }
9621
Sebastian Redla72462c2011-09-24 17:48:32 +00009622 // Special diagnostic for failure to convert an initializer list, since
9623 // telling the user that it has type void is not useful.
9624 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9625 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9626 << (unsigned) FnKind << FnDesc
9627 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9628 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009629 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009630 return;
9631 }
9632
John McCall6d174642010-01-23 08:10:49 +00009633 // Diagnose references or pointers to incomplete types differently,
9634 // since it's far from impossible that the incompleteness triggered
9635 // the failure.
9636 QualType TempFromTy = FromTy.getNonReferenceType();
9637 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9638 TempFromTy = PTy->getPointeeType();
9639 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009640 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009641 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9642 << (unsigned) FnKind << FnDesc
9643 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009644 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9645 << (unsigned) (Cand->Fix.Kind);
9646
Richard Smith5179eb72016-06-28 19:03:57 +00009647 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009648 return;
9649 }
9650
Douglas Gregor56f2e342010-06-30 23:01:39 +00009651 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009652 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009653 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9654 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9655 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9656 FromPtrTy->getPointeeType()) &&
9657 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9658 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009659 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009660 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009661 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009662 }
9663 } else if (const ObjCObjectPointerType *FromPtrTy
9664 = FromTy->getAs<ObjCObjectPointerType>()) {
9665 if (const ObjCObjectPointerType *ToPtrTy
9666 = ToTy->getAs<ObjCObjectPointerType>())
9667 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9668 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9669 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9670 FromPtrTy->getPointeeType()) &&
9671 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009672 BaseToDerivedConversion = 2;
9673 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009674 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9675 !FromTy->isIncompleteType() &&
9676 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009677 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009678 BaseToDerivedConversion = 3;
9679 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9680 ToTy.getNonReferenceType().getCanonicalType() ==
9681 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009682 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9683 << (unsigned) FnKind << FnDesc
9684 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9685 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009686 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009687 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009688 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009690
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009691 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009692 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009693 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009694 << (unsigned) FnKind << FnDesc
9695 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009696 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009697 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009698 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009699 return;
9700 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009701
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009702 if (isa<ObjCObjectPointerType>(CFromTy) &&
9703 isa<PointerType>(CToTy)) {
9704 Qualifiers FromQs = CFromTy.getQualifiers();
9705 Qualifiers ToQs = CToTy.getQualifiers();
9706 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9707 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9708 << (unsigned) FnKind << FnDesc
9709 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9710 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009711 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009712 return;
9713 }
9714 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009715
9716 if (TakingCandidateAddress &&
9717 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9718 return;
9719
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009720 // Emit the generic diagnostic and, optionally, add the hints to it.
9721 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9722 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009723 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009724 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9725 << (unsigned) (Cand->Fix.Kind);
9726
9727 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009728 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9729 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009730 FDiag << *HI;
9731 S.Diag(Fn->getLocation(), FDiag);
9732
Richard Smith5179eb72016-06-28 19:03:57 +00009733 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009734}
9735
Larisse Voufo98b20f12013-07-19 23:00:19 +00009736/// Additional arity mismatch diagnosis specific to a function overload
9737/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9738/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009739static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9740 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009741 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009742 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009743
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009744 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009745 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009746 // right number of arguments, because only overloaded operators have
9747 // the weird behavior of overloading member and non-member functions.
9748 // Just don't report anything.
9749 if (Fn->isInvalidDecl() &&
9750 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009751 return true;
9752
9753 if (NumArgs < MinParams) {
9754 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9755 (Cand->FailureKind == ovl_fail_bad_deduction &&
9756 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9757 } else {
9758 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9759 (Cand->FailureKind == ovl_fail_bad_deduction &&
9760 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9761 }
9762
9763 return false;
9764}
9765
9766/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009767static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9768 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009769 assert(isa<FunctionDecl>(D) &&
9770 "The templated declaration should at least be a function"
9771 " when diagnosing bad template argument deduction due to too many"
9772 " or too few arguments");
9773
9774 FunctionDecl *Fn = cast<FunctionDecl>(D);
9775
9776 // TODO: treat calls to a missing default constructor as a special case
9777 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9778 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009779
John McCall6a61b522010-01-13 09:16:55 +00009780 // at least / at most / exactly
9781 unsigned mode, modeCount;
9782 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009783 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9784 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009785 mode = 0; // "at least"
9786 else
9787 mode = 2; // "exactly"
9788 modeCount = MinParams;
9789 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009790 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009791 mode = 1; // "at most"
9792 else
9793 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009794 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009795 }
9796
9797 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009798 OverloadCandidateKind FnKind =
9799 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009800
Richard Smith10ff50d2012-05-11 05:16:41 +00009801 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9802 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009803 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9804 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009805 else
9806 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009807 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9808 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009809 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009810}
9811
Larisse Voufo98b20f12013-07-19 23:00:19 +00009812/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009813static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9814 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009815 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009816 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009817}
Larisse Voufo47c08452013-07-19 22:53:23 +00009818
Richard Smith17c00b42014-11-12 01:24:00 +00009819static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009820 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9821 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009822 llvm_unreachable("Unsupported: Getting the described template declaration"
9823 " for bad deduction diagnosis");
9824}
9825
9826/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009827static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009828 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009829 unsigned NumArgs,
9830 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009831 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009832 NamedDecl *ParamD;
9833 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9834 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9835 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009836 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009837 case Sema::TDK_Success:
9838 llvm_unreachable("TDK_success while diagnosing bad deduction");
9839
9840 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009841 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009842 S.Diag(Templated->getLocation(),
9843 diag::note_ovl_candidate_incomplete_deduction)
9844 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009845 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009846 return;
9847 }
9848
John McCall42d7d192010-08-05 09:05:08 +00009849 case Sema::TDK_Underqualified: {
9850 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9851 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9852
Larisse Voufo98b20f12013-07-19 23:00:19 +00009853 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009854
9855 // Param will have been canonicalized, but it should just be a
9856 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009857 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009858 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009859 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009860 assert(S.Context.hasSameType(Param, NonCanonParam));
9861
9862 // Arg has also been canonicalized, but there's nothing we can do
9863 // about that. It also doesn't matter as much, because it won't
9864 // have any template parameters in it (because deduction isn't
9865 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009866 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009867
Larisse Voufo98b20f12013-07-19 23:00:19 +00009868 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9869 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009870 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009871 return;
9872 }
9873
9874 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009875 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009876 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009877 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009878 which = 0;
Richard Smith593d6a12016-12-23 01:30:39 +00009879 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9880 // Deduction might have failed because we deduced arguments of two
9881 // different types for a non-type template parameter.
9882 // FIXME: Use a different TDK value for this.
9883 QualType T1 =
9884 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9885 QualType T2 =
9886 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9887 if (!S.Context.hasSameType(T1, T2)) {
9888 S.Diag(Templated->getLocation(),
9889 diag::note_ovl_candidate_inconsistent_deduction_types)
9890 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9891 << *DeductionFailure.getSecondArg() << T2;
9892 MaybeEmitInheritedConstructorNote(S, Found);
9893 return;
9894 }
9895
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009896 which = 1;
Richard Smith593d6a12016-12-23 01:30:39 +00009897 } else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009898 which = 2;
9899 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009900
Larisse Voufo98b20f12013-07-19 23:00:19 +00009901 S.Diag(Templated->getLocation(),
9902 diag::note_ovl_candidate_inconsistent_deduction)
9903 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9904 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009905 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009906 return;
9907 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009908
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009909 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009910 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009911 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009912 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009913 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009914 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009915 else {
9916 int index = 0;
9917 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9918 index = TTP->getIndex();
9919 else if (NonTypeTemplateParmDecl *NTTP
9920 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9921 index = NTTP->getIndex();
9922 else
9923 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009924 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009925 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009926 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009927 }
Richard Smith5179eb72016-06-28 19:03:57 +00009928 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009929 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009930
Douglas Gregor02eb4832010-05-08 18:13:28 +00009931 case Sema::TDK_TooManyArguments:
9932 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009933 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009934 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009935
9936 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009937 S.Diag(Templated->getLocation(),
9938 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009939 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009940 return;
9941
9942 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009943 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009944 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009945 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009946 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009947 TemplateArgString = " ";
9948 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009949 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009950 }
9951
Richard Smith6f8d2c62012-05-09 05:17:00 +00009952 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009953 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009954 if (PDiag && PDiag->second.getDiagID() ==
9955 diag::err_typename_nested_not_found_enable_if) {
9956 // FIXME: Use the source range of the condition, and the fully-qualified
9957 // name of the enable_if template. These are both present in PDiag.
9958 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9959 << "'enable_if'" << TemplateArgString;
9960 return;
9961 }
9962
Richard Smith9ca64612012-05-07 09:03:25 +00009963 // Format the SFINAE diagnostic into the argument string.
9964 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9965 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009966 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009967 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009968 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009969 SFINAEArgString = ": ";
9970 R = SourceRange(PDiag->first, PDiag->first);
9971 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9972 }
9973
Larisse Voufo98b20f12013-07-19 23:00:19 +00009974 S.Diag(Templated->getLocation(),
9975 diag::note_ovl_candidate_substitution_failure)
9976 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009977 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009978 return;
9979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009980
Richard Smithc92d2062017-01-05 23:02:44 +00009981 case Sema::TDK_DeducedMismatch:
9982 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +00009983 // Format the template argument list into the argument string.
9984 SmallString<128> TemplateArgString;
9985 if (TemplateArgumentList *Args =
9986 DeductionFailure.getTemplateArgumentList()) {
9987 TemplateArgString = " ";
9988 TemplateArgString += S.getTemplateArgumentBindingsText(
9989 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9990 }
9991
9992 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9993 << (*DeductionFailure.getCallArgIndex() + 1)
9994 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
Richard Smithc92d2062017-01-05 23:02:44 +00009995 << TemplateArgString
9996 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
Richard Smith9b534542015-12-31 02:02:54 +00009997 break;
9998 }
9999
Richard Trieue3732352013-04-08 21:11:40 +000010000 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +000010001 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010002 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10003 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +000010004 if (FirstTA.getKind() == TemplateArgument::Template &&
10005 SecondTA.getKind() == TemplateArgument::Template) {
10006 TemplateName FirstTN = FirstTA.getAsTemplate();
10007 TemplateName SecondTN = SecondTA.getAsTemplate();
10008 if (FirstTN.getKind() == TemplateName::Template &&
10009 SecondTN.getKind() == TemplateName::Template) {
10010 if (FirstTN.getAsTemplateDecl()->getName() ==
10011 SecondTN.getAsTemplateDecl()->getName()) {
10012 // FIXME: This fixes a bad diagnostic where both templates are named
10013 // the same. This particular case is a bit difficult since:
10014 // 1) It is passed as a string to the diagnostic printer.
10015 // 2) The diagnostic printer only attempts to find a better
10016 // name for types, not decls.
10017 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010018 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +000010019 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10020 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10021 return;
10022 }
10023 }
10024 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010025
10026 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10027 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10028 return;
10029
Faisal Vali2b391ab2013-09-26 19:54:12 +000010030 // FIXME: For generic lambda parameters, check if the function is a lambda
10031 // call operator, and if so, emit a prettier and more informative
10032 // diagnostic that mentions 'auto' and lambda in addition to
10033 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +000010034 S.Diag(Templated->getLocation(),
10035 diag::note_ovl_candidate_non_deduced_mismatch)
10036 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +000010037 return;
Richard Trieue3732352013-04-08 21:11:40 +000010038 }
John McCall8b9ed552010-02-01 18:53:26 +000010039 // TODO: diagnose these individually, then kill off
10040 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +000010041 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010042 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +000010043 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +000010044 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010045 case Sema::TDK_CUDATargetMismatch:
10046 S.Diag(Templated->getLocation(),
10047 diag::note_cuda_ovl_candidate_target_mismatch);
10048 return;
John McCall8b9ed552010-02-01 18:53:26 +000010049 }
10050}
10051
Larisse Voufo98b20f12013-07-19 23:00:19 +000010052/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +000010053static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010054 unsigned NumArgs,
10055 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010056 unsigned TDK = Cand->DeductionFailure.Result;
10057 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10058 if (CheckArityMismatch(S, Cand, NumArgs))
10059 return;
10060 }
Richard Smithc2bebe92016-05-11 20:37:46 +000010061 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010062 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010063}
10064
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010065/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +000010066static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010067 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10068 FunctionDecl *Callee = Cand->Function;
10069
10070 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10071 CalleeTarget = S.IdentifyCUDATarget(Callee);
10072
10073 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +000010074 OverloadCandidateKind FnKind =
10075 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010076
10077 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010078 << (unsigned)FnKind << CalleeTarget << CallerTarget;
10079
10080 // This could be an implicit constructor for which we could not infer the
10081 // target due to a collsion. Diagnose that case.
10082 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10083 if (Meth != nullptr && Meth->isImplicit()) {
10084 CXXRecordDecl *ParentClass = Meth->getParent();
10085 Sema::CXXSpecialMember CSM;
10086
10087 switch (FnKind) {
10088 default:
10089 return;
10090 case oc_implicit_default_constructor:
10091 CSM = Sema::CXXDefaultConstructor;
10092 break;
10093 case oc_implicit_copy_constructor:
10094 CSM = Sema::CXXCopyConstructor;
10095 break;
10096 case oc_implicit_move_constructor:
10097 CSM = Sema::CXXMoveConstructor;
10098 break;
10099 case oc_implicit_copy_assignment:
10100 CSM = Sema::CXXCopyAssignment;
10101 break;
10102 case oc_implicit_move_assignment:
10103 CSM = Sema::CXXMoveAssignment;
10104 break;
10105 };
10106
10107 bool ConstRHS = false;
10108 if (Meth->getNumParams()) {
10109 if (const ReferenceType *RT =
10110 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10111 ConstRHS = RT->getPointeeType().isConstQualified();
10112 }
10113 }
10114
10115 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10116 /* ConstRHS */ ConstRHS,
10117 /* Diagnose */ true);
10118 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010119}
10120
Richard Smith17c00b42014-11-12 01:24:00 +000010121static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010122 FunctionDecl *Callee = Cand->Function;
10123 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10124
10125 S.Diag(Callee->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000010126 diag::note_ovl_candidate_disabled_by_function_cond_attr)
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010127 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10128}
10129
Yaxun Liu5b746652016-12-18 05:18:55 +000010130static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10131 FunctionDecl *Callee = Cand->Function;
10132
10133 S.Diag(Callee->getLocation(),
10134 diag::note_ovl_candidate_disabled_by_extension);
10135}
10136
John McCall8b9ed552010-02-01 18:53:26 +000010137/// Generates a 'note' diagnostic for an overload candidate. We've
10138/// already generated a primary error at the call site.
10139///
10140/// It really does need to be a single diagnostic with its caret
10141/// pointed at the candidate declaration. Yes, this creates some
10142/// major challenges of technical writing. Yes, this makes pointing
10143/// out problems with specific arguments quite awkward. It's still
10144/// better than generating twenty screens of text for every failed
10145/// overload.
10146///
10147/// It would be great to be able to express per-candidate problems
10148/// more richly for those diagnostic clients that cared, but we'd
10149/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +000010150static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010151 unsigned NumArgs,
10152 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +000010153 FunctionDecl *Fn = Cand->Function;
10154
John McCall12f97bc2010-01-08 04:41:39 +000010155 // Note deleted candidates, but only if they're viable.
George Burgess IV177399e2017-01-09 04:12:14 +000010156 if (Cand->Viable) {
10157 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10158 std::string FnDesc;
10159 OverloadCandidateKind FnKind =
Richard Smithc2bebe92016-05-11 20:37:46 +000010160 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +000010161
George Burgess IV177399e2017-01-09 04:12:14 +000010162 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10163 << FnKind << FnDesc
10164 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10165 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10166 return;
10167 }
10168 if (isCandidateUnavailableDueToDiagnoseIf(*Cand)) {
10169 auto *A = Cand->DiagnoseIfInfo.get<DiagnoseIfAttr *>();
10170 assert(A->isError() && "Non-error diagnose_if disables a candidate?");
10171 S.Diag(Cand->Function->getLocation(),
10172 diag::note_ovl_candidate_disabled_by_function_cond_attr)
10173 << A->getCond()->getSourceRange() << A->getMessage();
10174 return;
10175 }
John McCall12f97bc2010-01-08 04:41:39 +000010176
George Burgess IV177399e2017-01-09 04:12:14 +000010177 // We don't really have anything else to say about viable candidates.
Richard Smithc2bebe92016-05-11 20:37:46 +000010178 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010179 return;
10180 }
John McCall0d1da222010-01-12 00:44:57 +000010181
John McCall6a61b522010-01-13 09:16:55 +000010182 switch (Cand->FailureKind) {
10183 case ovl_fail_too_many_arguments:
10184 case ovl_fail_too_few_arguments:
10185 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +000010186
John McCall6a61b522010-01-13 09:16:55 +000010187 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +000010188 return DiagnoseBadDeduction(S, Cand, NumArgs,
10189 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +000010190
John McCall578a1f82014-12-14 01:46:53 +000010191 case ovl_fail_illegal_constructor: {
10192 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10193 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +000010194 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +000010195 return;
10196 }
10197
John McCallfe796dd2010-01-23 05:17:32 +000010198 case ovl_fail_trivial_conversion:
10199 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +000010200 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +000010201 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010202
John McCall65eb8792010-02-25 01:37:24 +000010203 case ovl_fail_bad_conversion: {
10204 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Richard Smith6eedfe72017-01-09 08:01:21 +000010205 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +000010206 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010207 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010208
John McCall6a61b522010-01-13 09:16:55 +000010209 // FIXME: this currently happens when we're called from SemaInit
10210 // when user-conversion overload fails. Figure out how to handle
10211 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +000010212 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010213 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010214
10215 case ovl_fail_bad_target:
10216 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010217
10218 case ovl_fail_enable_if:
10219 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +000010220
Yaxun Liu5b746652016-12-18 05:18:55 +000010221 case ovl_fail_ext_disabled:
10222 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10223
Richard Smithf9c59b72017-01-08 21:45:44 +000010224 case ovl_fail_inhctor_slice:
10225 S.Diag(Fn->getLocation(),
10226 diag::note_ovl_candidate_inherited_constructor_slice);
10227 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10228 return;
10229
George Burgess IV7204ed92016-01-07 02:26:57 +000010230 case ovl_fail_addr_not_available: {
10231 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10232 (void)Available;
10233 assert(!Available);
10234 break;
10235 }
John McCall65eb8792010-02-25 01:37:24 +000010236 }
John McCalld3224162010-01-08 00:58:21 +000010237}
10238
Richard Smith17c00b42014-11-12 01:24:00 +000010239static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +000010240 // Desugar the type of the surrogate down to a function type,
10241 // retaining as many typedefs as possible while still showing
10242 // the function type (and, therefore, its parameter types).
10243 QualType FnType = Cand->Surrogate->getConversionType();
10244 bool isLValueReference = false;
10245 bool isRValueReference = false;
10246 bool isPointer = false;
10247 if (const LValueReferenceType *FnTypeRef =
10248 FnType->getAs<LValueReferenceType>()) {
10249 FnType = FnTypeRef->getPointeeType();
10250 isLValueReference = true;
10251 } else if (const RValueReferenceType *FnTypeRef =
10252 FnType->getAs<RValueReferenceType>()) {
10253 FnType = FnTypeRef->getPointeeType();
10254 isRValueReference = true;
10255 }
10256 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10257 FnType = FnTypePtr->getPointeeType();
10258 isPointer = true;
10259 }
10260 // Desugar down to a function type.
10261 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10262 // Reconstruct the pointer/reference as appropriate.
10263 if (isPointer) FnType = S.Context.getPointerType(FnType);
10264 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10265 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10266
10267 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10268 << FnType;
10269}
10270
Richard Smith17c00b42014-11-12 01:24:00 +000010271static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10272 SourceLocation OpLoc,
10273 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010274 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +000010275 std::string TypeStr("operator");
10276 TypeStr += Opc;
10277 TypeStr += "(";
10278 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Richard Smith6eedfe72017-01-09 08:01:21 +000010279 if (Cand->Conversions.size() == 1) {
John McCalld3224162010-01-08 00:58:21 +000010280 TypeStr += ")";
10281 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10282 } else {
10283 TypeStr += ", ";
10284 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
10285 TypeStr += ")";
10286 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10287 }
10288}
10289
Richard Smith17c00b42014-11-12 01:24:00 +000010290static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10291 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010292 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
John McCall0d1da222010-01-12 00:44:57 +000010293 if (ICS.isBad()) break; // all meaningless after first invalid
10294 if (!ICS.isAmbiguous()) continue;
10295
Richard Smithc2bebe92016-05-11 20:37:46 +000010296 ICS.DiagnoseAmbiguousConversion(
10297 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +000010298 }
10299}
10300
Larisse Voufo98b20f12013-07-19 23:00:19 +000010301static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +000010302 if (Cand->Function)
10303 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010304 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010305 return Cand->Surrogate->getLocation();
10306 return SourceLocation();
10307}
10308
Larisse Voufo98b20f12013-07-19 23:00:19 +000010309static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010310 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010311 case Sema::TDK_Success:
Richard Smith6eedfe72017-01-09 08:01:21 +000010312 case Sema::TDK_NonDependentConversionFailure:
10313 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010314
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010315 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010316 case Sema::TDK_Incomplete:
10317 return 1;
10318
10319 case Sema::TDK_Underqualified:
10320 case Sema::TDK_Inconsistent:
10321 return 2;
10322
10323 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010324 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +000010325 case Sema::TDK_DeducedMismatchNested:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010326 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010327 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010328 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010329 return 3;
10330
10331 case Sema::TDK_InstantiationDepth:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010332 return 4;
10333
10334 case Sema::TDK_InvalidExplicitArguments:
10335 return 5;
10336
10337 case Sema::TDK_TooManyArguments:
10338 case Sema::TDK_TooFewArguments:
10339 return 6;
10340 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010341 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010342}
10343
Richard Smith17c00b42014-11-12 01:24:00 +000010344namespace {
John McCallad2587a2010-01-12 00:48:53 +000010345struct CompareOverloadCandidatesForDisplay {
10346 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010347 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010348 size_t NumArgs;
10349
Richard Smith0f59cb32015-12-18 21:45:41 +000010350 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010351 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +000010352
10353 bool operator()(const OverloadCandidate *L,
10354 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010355 // Fast-path this check.
10356 if (L == R) return false;
10357
John McCall12f97bc2010-01-08 04:41:39 +000010358 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010359 if (L->Viable) {
10360 if (!R->Viable) return true;
10361
10362 // TODO: introduce a tri-valued comparison for overload
10363 // candidates. Would be more worthwhile if we had a sort
10364 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +000010365 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10366 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +000010367 } else if (R->Viable)
10368 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010369
John McCall3712d9e2010-01-15 23:32:50 +000010370 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010371
John McCall3712d9e2010-01-15 23:32:50 +000010372 // Criteria by which we can sort non-viable candidates:
10373 if (!L->Viable) {
10374 // 1. Arity mismatches come after other candidates.
10375 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010376 L->FailureKind == ovl_fail_too_few_arguments) {
10377 if (R->FailureKind == ovl_fail_too_many_arguments ||
10378 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010379 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10380 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10381 if (LDist == RDist) {
10382 if (L->FailureKind == R->FailureKind)
10383 // Sort non-surrogates before surrogates.
10384 return !L->IsSurrogate && R->IsSurrogate;
10385 // Sort candidates requiring fewer parameters than there were
10386 // arguments given after candidates requiring more parameters
10387 // than there were arguments given.
10388 return L->FailureKind == ovl_fail_too_many_arguments;
10389 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010390 return LDist < RDist;
10391 }
John McCall3712d9e2010-01-15 23:32:50 +000010392 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010393 }
John McCall3712d9e2010-01-15 23:32:50 +000010394 if (R->FailureKind == ovl_fail_too_many_arguments ||
10395 R->FailureKind == ovl_fail_too_few_arguments)
10396 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010397
John McCallfe796dd2010-01-23 05:17:32 +000010398 // 2. Bad conversions come first and are ordered by the number
10399 // of bad conversions and quality of good conversions.
10400 if (L->FailureKind == ovl_fail_bad_conversion) {
10401 if (R->FailureKind != ovl_fail_bad_conversion)
10402 return true;
10403
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010404 // The conversion that can be fixed with a smaller number of changes,
10405 // comes first.
10406 unsigned numLFixes = L->Fix.NumConversionsFixed;
10407 unsigned numRFixes = R->Fix.NumConversionsFixed;
10408 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10409 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010410 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010411 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010412 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010413
John McCallfe796dd2010-01-23 05:17:32 +000010414 // If there's any ordering between the defined conversions...
10415 // FIXME: this might not be transitive.
Richard Smith6eedfe72017-01-09 08:01:21 +000010416 assert(L->Conversions.size() == R->Conversions.size());
John McCallfe796dd2010-01-23 05:17:32 +000010417
10418 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010419 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Richard Smith6eedfe72017-01-09 08:01:21 +000010420 for (unsigned E = L->Conversions.size(); I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010421 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010422 L->Conversions[I],
10423 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010424 case ImplicitConversionSequence::Better:
10425 leftBetter++;
10426 break;
10427
10428 case ImplicitConversionSequence::Worse:
10429 leftBetter--;
10430 break;
10431
10432 case ImplicitConversionSequence::Indistinguishable:
10433 break;
10434 }
10435 }
10436 if (leftBetter > 0) return true;
10437 if (leftBetter < 0) return false;
10438
10439 } else if (R->FailureKind == ovl_fail_bad_conversion)
10440 return false;
10441
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010442 if (L->FailureKind == ovl_fail_bad_deduction) {
10443 if (R->FailureKind != ovl_fail_bad_deduction)
10444 return true;
10445
10446 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10447 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010448 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010449 } else if (R->FailureKind == ovl_fail_bad_deduction)
10450 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010451
John McCall3712d9e2010-01-15 23:32:50 +000010452 // TODO: others?
10453 }
10454
10455 // Sort everything else by location.
10456 SourceLocation LLoc = GetLocationForCandidate(L);
10457 SourceLocation RLoc = GetLocationForCandidate(R);
10458
10459 // Put candidates without locations (e.g. builtins) at the end.
10460 if (LLoc.isInvalid()) return false;
10461 if (RLoc.isInvalid()) return true;
10462
10463 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010464 }
10465};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010466}
John McCall12f97bc2010-01-08 04:41:39 +000010467
John McCallfe796dd2010-01-23 05:17:32 +000010468/// CompleteNonViableCandidate - Normally, overload resolution only
Richard Smith6eedfe72017-01-09 08:01:21 +000010469/// computes up to the first bad conversion. Produces the FixIt set if
10470/// possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010471static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10472 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010473 assert(!Cand->Viable);
10474
10475 // Don't do anything on failures other than bad conversion.
10476 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10477
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010478 // We only want the FixIts if all the arguments can be corrected.
10479 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010480 // Use a implicit copy initialization to check conversion fixes.
10481 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010482
Richard Smith6eedfe72017-01-09 08:01:21 +000010483 // Attempt to fix the bad conversion.
10484 unsigned ConvCount = Cand->Conversions.size();
10485 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10486 ++ConvIdx) {
John McCallfe796dd2010-01-23 05:17:32 +000010487 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
Richard Smith6eedfe72017-01-09 08:01:21 +000010488 if (Cand->Conversions[ConvIdx].isInitialized() &&
10489 Cand->Conversions[ConvIdx].isBad()) {
10490 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
John McCallfe796dd2010-01-23 05:17:32 +000010491 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010492 }
John McCallfe796dd2010-01-23 05:17:32 +000010493 }
10494
Douglas Gregoradc7a702010-04-16 17:45:54 +000010495 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010496 // operation somehow.
10497 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010498
Richard Smith14ead302017-01-10 20:19:21 +000010499 unsigned ConvIdx = 0;
10500 ArrayRef<QualType> ParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010501
10502 if (Cand->IsSurrogate) {
10503 QualType ConvType
10504 = Cand->Surrogate->getConversionType().getNonReferenceType();
10505 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10506 ConvType = ConvPtrType->getPointeeType();
Richard Smith14ead302017-01-10 20:19:21 +000010507 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10508 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10509 ConvIdx = 1;
John McCallfe796dd2010-01-23 05:17:32 +000010510 } else if (Cand->Function) {
Richard Smith14ead302017-01-10 20:19:21 +000010511 ParamTypes =
10512 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
John McCallfe796dd2010-01-23 05:17:32 +000010513 if (isa<CXXMethodDecl>(Cand->Function) &&
Richard Smith14ead302017-01-10 20:19:21 +000010514 !isa<CXXConstructorDecl>(Cand->Function)) {
10515 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10516 ConvIdx = 1;
Richard Smith6eedfe72017-01-09 08:01:21 +000010517 }
Richard Smith14ead302017-01-10 20:19:21 +000010518 } else {
10519 // Builtin operator.
10520 assert(ConvCount <= 3);
10521 ParamTypes = Cand->BuiltinTypes.ParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010522 }
10523
10524 // Fill in the rest of the conversions.
Richard Smith14ead302017-01-10 20:19:21 +000010525 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010526 if (Cand->Conversions[ConvIdx].isInitialized()) {
Richard Smith14ead302017-01-10 20:19:21 +000010527 // We've already checked this conversion.
10528 } else if (ArgIdx < ParamTypes.size()) {
10529 if (ParamTypes[ArgIdx]->isDependentType())
Richard Smith6eedfe72017-01-09 08:01:21 +000010530 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10531 Args[ArgIdx]->getType());
10532 else {
10533 Cand->Conversions[ConvIdx] =
Richard Smith14ead302017-01-10 20:19:21 +000010534 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
Richard Smith6eedfe72017-01-09 08:01:21 +000010535 SuppressUserConversions,
10536 /*InOverloadResolution=*/true,
10537 /*AllowObjCWritebackConversion=*/
10538 S.getLangOpts().ObjCAutoRefCount);
10539 // Store the FixIt in the candidate if it exists.
10540 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10541 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10542 }
10543 } else
John McCallfe796dd2010-01-23 05:17:32 +000010544 Cand->Conversions[ConvIdx].setEllipsis();
10545 }
10546}
10547
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010548/// PrintOverloadCandidates - When overload resolution fails, prints
10549/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010550/// set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010551void OverloadCandidateSet::NoteCandidates(
10552 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10553 StringRef Opc, SourceLocation OpLoc,
10554 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010555 // Sort the candidates by viability and position. Sorting directly would
10556 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010557 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010558 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10559 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010560 if (!Filter(*Cand))
10561 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010562 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010563 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010564 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010565 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010566 if (Cand->Function || Cand->IsSurrogate)
10567 Cands.push_back(Cand);
10568 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10569 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010570 }
10571 }
10572
John McCallad2587a2010-01-12 00:48:53 +000010573 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010574 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010575
John McCall0d1da222010-01-12 00:44:57 +000010576 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010577
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010578 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010579 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010580 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010581 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10582 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010583
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010584 // Set an arbitrary limit on the number of candidate functions we'll spam
10585 // the user with. FIXME: This limit should depend on details of the
10586 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010587 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010588 break;
10589 }
10590 ++CandsShown;
10591
John McCalld3224162010-01-08 00:58:21 +000010592 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010593 NoteFunctionCandidate(S, Cand, Args.size(),
10594 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010595 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010596 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010597 else {
10598 assert(Cand->Viable &&
10599 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010600 // Generally we only see ambiguities including viable builtin
10601 // operators if overload resolution got screwed up by an
10602 // ambiguous user-defined conversion.
10603 //
10604 // FIXME: It's quite possible for different conversions to see
10605 // different ambiguities, though.
10606 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010607 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010608 ReportedAmbiguousConversions = true;
10609 }
John McCalld3224162010-01-08 00:58:21 +000010610
John McCall0d1da222010-01-12 00:44:57 +000010611 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010612 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010613 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010614 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010615
10616 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010617 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010618}
10619
Larisse Voufo98b20f12013-07-19 23:00:19 +000010620static SourceLocation
10621GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10622 return Cand->Specialization ? Cand->Specialization->getLocation()
10623 : SourceLocation();
10624}
10625
Richard Smith17c00b42014-11-12 01:24:00 +000010626namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010627struct CompareTemplateSpecCandidatesForDisplay {
10628 Sema &S;
10629 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10630
10631 bool operator()(const TemplateSpecCandidate *L,
10632 const TemplateSpecCandidate *R) {
10633 // Fast-path this check.
10634 if (L == R)
10635 return false;
10636
10637 // Assuming that both candidates are not matches...
10638
10639 // Sort by the ranking of deduction failures.
10640 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10641 return RankDeductionFailure(L->DeductionFailure) <
10642 RankDeductionFailure(R->DeductionFailure);
10643
10644 // Sort everything else by location.
10645 SourceLocation LLoc = GetLocationForCandidate(L);
10646 SourceLocation RLoc = GetLocationForCandidate(R);
10647
10648 // Put candidates without locations (e.g. builtins) at the end.
10649 if (LLoc.isInvalid())
10650 return false;
10651 if (RLoc.isInvalid())
10652 return true;
10653
10654 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10655 }
10656};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010657}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010658
10659/// Diagnose a template argument deduction failure.
10660/// We are treating these failures as overload failures due to bad
10661/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010662void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10663 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010664 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010665 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010666}
10667
10668void TemplateSpecCandidateSet::destroyCandidates() {
10669 for (iterator i = begin(), e = end(); i != e; ++i) {
10670 i->DeductionFailure.Destroy();
10671 }
10672}
10673
10674void TemplateSpecCandidateSet::clear() {
10675 destroyCandidates();
10676 Candidates.clear();
10677}
10678
10679/// NoteCandidates - When no template specialization match is found, prints
10680/// diagnostic messages containing the non-matching specializations that form
10681/// the candidate set.
10682/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10683/// OCD == OCD_AllCandidates and Cand->Viable == false.
10684void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10685 // Sort the candidates by position (assuming no candidate is a match).
10686 // Sorting directly would be prohibitive, so we make a set of pointers
10687 // and sort those.
10688 SmallVector<TemplateSpecCandidate *, 32> Cands;
10689 Cands.reserve(size());
10690 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10691 if (Cand->Specialization)
10692 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010693 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010694 // in general, want to list every possible builtin candidate.
10695 }
10696
10697 std::sort(Cands.begin(), Cands.end(),
10698 CompareTemplateSpecCandidatesForDisplay(S));
10699
10700 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10701 // for generalization purposes (?).
10702 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10703
10704 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10705 unsigned CandsShown = 0;
10706 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10707 TemplateSpecCandidate *Cand = *I;
10708
10709 // Set an arbitrary limit on the number of candidates we'll spam
10710 // the user with. FIXME: This limit should depend on details of the
10711 // candidate list.
10712 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10713 break;
10714 ++CandsShown;
10715
10716 assert(Cand->Specialization &&
10717 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010718 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010719 }
10720
10721 if (I != E)
10722 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10723}
10724
Douglas Gregorb491ed32011-02-19 21:32:49 +000010725// [PossiblyAFunctionType] --> [Return]
10726// NonFunctionType --> NonFunctionType
10727// R (A) --> R(A)
10728// R (*)(A) --> R (A)
10729// R (&)(A) --> R (A)
10730// R (S::*)(A) --> R (A)
10731QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10732 QualType Ret = PossiblyAFunctionType;
10733 if (const PointerType *ToTypePtr =
10734 PossiblyAFunctionType->getAs<PointerType>())
10735 Ret = ToTypePtr->getPointeeType();
10736 else if (const ReferenceType *ToTypeRef =
10737 PossiblyAFunctionType->getAs<ReferenceType>())
10738 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010739 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010740 PossiblyAFunctionType->getAs<MemberPointerType>())
10741 Ret = MemTypePtr->getPointeeType();
10742 Ret =
10743 Context.getCanonicalType(Ret).getUnqualifiedType();
10744 return Ret;
10745}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010746
Richard Smith9095e5b2016-11-01 01:31:23 +000010747static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10748 bool Complain = true) {
10749 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10750 S.DeduceReturnType(FD, Loc, Complain))
10751 return true;
10752
10753 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10754 if (S.getLangOpts().CPlusPlus1z &&
10755 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10756 !S.ResolveExceptionSpec(Loc, FPT))
10757 return true;
10758
10759 return false;
10760}
10761
Richard Smith17c00b42014-11-12 01:24:00 +000010762namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010763// A helper class to help with address of function resolution
10764// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010765class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010766 Sema& S;
10767 Expr* SourceExpr;
10768 const QualType& TargetType;
10769 QualType TargetFunctionType; // Extracted function type from target type
10770
10771 bool Complain;
10772 //DeclAccessPair& ResultFunctionAccessPair;
10773 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010774
Douglas Gregorb491ed32011-02-19 21:32:49 +000010775 bool TargetTypeIsNonStaticMemberFunction;
10776 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010777 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010778 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010779
Douglas Gregorb491ed32011-02-19 21:32:49 +000010780 OverloadExpr::FindResult OvlExprInfo;
10781 OverloadExpr *OvlExpr;
10782 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010783 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010784 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010785
Douglas Gregorb491ed32011-02-19 21:32:49 +000010786public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010787 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10788 const QualType &TargetType, bool Complain)
10789 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10790 Complain(Complain), Context(S.getASTContext()),
10791 TargetTypeIsNonStaticMemberFunction(
10792 !!TargetType->getAs<MemberPointerType>()),
10793 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010794 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010795 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010796 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10797 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010798 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010799 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010800
David Majnemera4f7c7a2013-08-01 06:13:59 +000010801 if (TargetFunctionType->isFunctionType()) {
10802 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10803 if (!UME->isImplicitAccess() &&
10804 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10805 StaticMemberFunctionFromBoundPointer = true;
10806 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10807 DeclAccessPair dap;
10808 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10809 OvlExpr, false, &dap)) {
10810 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10811 if (!Method->isStatic()) {
10812 // If the target type is a non-function type and the function found
10813 // is a non-static member function, pretend as if that was the
10814 // target, it's the only possible type to end up with.
10815 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010816
David Majnemera4f7c7a2013-08-01 06:13:59 +000010817 // And skip adding the function if its not in the proper form.
10818 // We'll diagnose this due to an empty set of functions.
10819 if (!OvlExprInfo.HasFormOfMemberPointer)
10820 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010821 }
10822
David Majnemera4f7c7a2013-08-01 06:13:59 +000010823 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010824 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010825 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010826 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010827
10828 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010829 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010830
Douglas Gregorb491ed32011-02-19 21:32:49 +000010831 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10832 // C++ [over.over]p4:
10833 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010834 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010835 if (FoundNonTemplateFunction)
10836 EliminateAllTemplateMatches();
10837 else
10838 EliminateAllExceptMostSpecializedTemplate();
10839 }
10840 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010841
Justin Lebar25c4a812016-03-29 16:24:16 +000010842 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010843 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010844 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010845
10846 bool hasComplained() const { return HasComplained; }
10847
Douglas Gregorb491ed32011-02-19 21:32:49 +000010848private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010849 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10850 QualType Discard;
10851 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010852 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010853 }
10854
George Burgess IV6da4c202016-03-23 02:33:58 +000010855 /// \return true if A is considered a better overload candidate for the
10856 /// desired type than B.
10857 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10858 // If A doesn't have exactly the correct type, we don't want to classify it
10859 // as "better" than anything else. This way, the user is required to
10860 // disambiguate for us if there are multiple candidates and no exact match.
10861 return candidateHasExactlyCorrectType(A) &&
10862 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010863 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010864 }
10865
10866 /// \return true if we were able to eliminate all but one overload candidate,
10867 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010868 bool eliminiateSuboptimalOverloadCandidates() {
10869 // Same algorithm as overload resolution -- one pass to pick the "best",
10870 // another pass to be sure that nothing is better than the best.
10871 auto Best = Matches.begin();
10872 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10873 if (isBetterCandidate(I->second, Best->second))
10874 Best = I;
10875
10876 const FunctionDecl *BestFn = Best->second;
10877 auto IsBestOrInferiorToBest = [this, BestFn](
10878 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10879 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10880 };
10881
10882 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10883 // option, so we can potentially give the user a better error
10884 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10885 return false;
10886 Matches[0] = *Best;
10887 Matches.resize(1);
10888 return true;
10889 }
10890
Douglas Gregorb491ed32011-02-19 21:32:49 +000010891 bool isTargetTypeAFunction() const {
10892 return TargetFunctionType->isFunctionType();
10893 }
10894
10895 // [ToType] [Return]
10896
10897 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10898 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10899 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10900 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10901 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10902 }
10903
10904 // return true if any matching specializations were found
10905 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10906 const DeclAccessPair& CurAccessFunPair) {
10907 if (CXXMethodDecl *Method
10908 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10909 // Skip non-static function templates when converting to pointer, and
10910 // static when converting to member pointer.
10911 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10912 return false;
10913 }
10914 else if (TargetTypeIsNonStaticMemberFunction)
10915 return false;
10916
10917 // C++ [over.over]p2:
10918 // If the name is a function template, template argument deduction is
10919 // done (14.8.2.2), and if the argument deduction succeeds, the
10920 // resulting template argument list is used to generate a single
10921 // function template specialization, which is added to the set of
10922 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010923 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010924 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010925 if (Sema::TemplateDeductionResult Result
10926 = S.DeduceTemplateArguments(FunctionTemplate,
10927 &OvlExplicitTemplateArgs,
10928 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000010929 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010930 // Make a note of the failed deduction for diagnostics.
10931 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010932 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010933 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010934 return false;
10935 }
10936
Douglas Gregor19a41f12013-04-17 08:45:07 +000010937 // Template argument deduction ensures that we have an exact match or
10938 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010939 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010940 assert(S.isSameOrCompatibleFunctionType(
10941 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010942 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010943
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010944 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010945 return false;
10946
Douglas Gregorb491ed32011-02-19 21:32:49 +000010947 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10948 return true;
10949 }
10950
10951 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10952 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010953 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010954 // Skip non-static functions when converting to pointer, and static
10955 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010956 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10957 return false;
10958 }
10959 else if (TargetTypeIsNonStaticMemberFunction)
10960 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010961
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010962 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010963 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010964 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010965 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010966 return false;
10967
Richard Smith2a7d4812013-05-04 07:00:32 +000010968 // If any candidate has a placeholder return type, trigger its deduction
10969 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000010970 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10971 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000010972 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010973 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010974 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010975
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010976 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010977 return false;
10978
George Burgess IV6da4c202016-03-23 02:33:58 +000010979 // If we're in C, we need to support types that aren't exactly identical.
10980 if (!S.getLangOpts().CPlusPlus ||
10981 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010982 Matches.push_back(std::make_pair(
10983 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010984 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010985 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010986 }
Mike Stump11289f42009-09-09 15:08:12 +000010987 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010988
10989 return false;
10990 }
10991
10992 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10993 bool Ret = false;
10994
10995 // If the overload expression doesn't have the form of a pointer to
10996 // member, don't try to convert it to a pointer-to-member type.
10997 if (IsInvalidFormOfPointerToMemberFunction())
10998 return false;
10999
11000 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11001 E = OvlExpr->decls_end();
11002 I != E; ++I) {
11003 // Look through any using declarations to find the underlying function.
11004 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11005
11006 // C++ [over.over]p3:
11007 // Non-member functions and static member functions match
11008 // targets of type "pointer-to-function" or "reference-to-function."
11009 // Nonstatic member functions match targets of
11010 // type "pointer-to-member-function."
11011 // Note that according to DR 247, the containing class does not matter.
11012 if (FunctionTemplateDecl *FunctionTemplate
11013 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11014 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11015 Ret = true;
11016 }
11017 // If we have explicit template arguments supplied, skip non-templates.
11018 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11019 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11020 Ret = true;
11021 }
11022 assert(Ret || Matches.empty());
11023 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011024 }
11025
Douglas Gregorb491ed32011-02-19 21:32:49 +000011026 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000011027 // [...] and any given function template specialization F1 is
11028 // eliminated if the set contains a second function template
11029 // specialization whose function template is more specialized
11030 // than the function template of F1 according to the partial
11031 // ordering rules of 14.5.5.2.
11032
11033 // The algorithm specified above is quadratic. We instead use a
11034 // two-pass algorithm (similar to the one used to identify the
11035 // best viable function in an overload set) that identifies the
11036 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000011037
11038 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11039 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11040 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011041
Larisse Voufo98b20f12013-07-19 23:00:19 +000011042 // TODO: It looks like FailedCandidates does not serve much purpose
11043 // here, since the no_viable diagnostic has index 0.
11044 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000011045 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000011046 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000011047 S.PDiag(diag::err_addr_ovl_ambiguous)
11048 << Matches[0].second->getDeclName(),
11049 S.PDiag(diag::note_ovl_candidate)
11050 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000011051 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011052
Douglas Gregorb491ed32011-02-19 21:32:49 +000011053 if (Result != MatchesCopy.end()) {
11054 // Make it the first and only element
11055 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11056 Matches[0].second = cast<FunctionDecl>(*Result);
11057 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000011058 } else
11059 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000011060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011061
Douglas Gregorb491ed32011-02-19 21:32:49 +000011062 void EliminateAllTemplateMatches() {
11063 // [...] any function template specializations in the set are
11064 // eliminated if the set also contains a non-template function, [...]
11065 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011066 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011067 ++I;
11068 else {
11069 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000011070 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011071 }
11072 }
11073 }
11074
Artem Belevich94a55e82015-09-22 17:22:59 +000011075 void EliminateSuboptimalCudaMatches() {
11076 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11077 }
11078
Douglas Gregorb491ed32011-02-19 21:32:49 +000011079public:
11080 void ComplainNoMatchesFound() const {
11081 assert(Matches.empty());
11082 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11083 << OvlExpr->getName() << TargetFunctionType
11084 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000011085 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000011086 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11087 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011088 else {
11089 // We have some deduction failure messages. Use them to diagnose
11090 // the function templates, and diagnose the non-template candidates
11091 // normally.
11092 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11093 IEnd = OvlExpr->decls_end();
11094 I != IEnd; ++I)
11095 if (FunctionDecl *Fun =
11096 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011097 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000011098 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011099 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011100 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11101 }
11102 }
11103
Douglas Gregorb491ed32011-02-19 21:32:49 +000011104 bool IsInvalidFormOfPointerToMemberFunction() const {
11105 return TargetTypeIsNonStaticMemberFunction &&
11106 !OvlExprInfo.HasFormOfMemberPointer;
11107 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011108
Douglas Gregorb491ed32011-02-19 21:32:49 +000011109 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11110 // TODO: Should we condition this on whether any functions might
11111 // have matched, or is it more appropriate to do that in callers?
11112 // TODO: a fixit wouldn't hurt.
11113 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11114 << TargetType << OvlExpr->getSourceRange();
11115 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011116
11117 bool IsStaticMemberFunctionFromBoundPointer() const {
11118 return StaticMemberFunctionFromBoundPointer;
11119 }
11120
11121 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11122 S.Diag(OvlExpr->getLocStart(),
11123 diag::err_invalid_form_pointer_member_function)
11124 << OvlExpr->getSourceRange();
11125 }
11126
Douglas Gregorb491ed32011-02-19 21:32:49 +000011127 void ComplainOfInvalidConversion() const {
11128 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11129 << OvlExpr->getName() << TargetType;
11130 }
11131
11132 void ComplainMultipleMatchesFound() const {
11133 assert(Matches.size() > 1);
11134 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11135 << OvlExpr->getName()
11136 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000011137 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11138 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011139 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011140
11141 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11142
Douglas Gregorb491ed32011-02-19 21:32:49 +000011143 int getNumMatches() const { return Matches.size(); }
11144
11145 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011146 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011147 return Matches[0].second;
11148 }
11149
11150 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011151 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011152 return &Matches[0].first;
11153 }
11154};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011155}
Richard Smith17c00b42014-11-12 01:24:00 +000011156
Douglas Gregorb491ed32011-02-19 21:32:49 +000011157/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11158/// an overloaded function (C++ [over.over]), where @p From is an
11159/// expression with overloaded function type and @p ToType is the type
11160/// we're trying to resolve to. For example:
11161///
11162/// @code
11163/// int f(double);
11164/// int f(int);
11165///
11166/// int (*pfd)(double) = f; // selects f(double)
11167/// @endcode
11168///
11169/// This routine returns the resulting FunctionDecl if it could be
11170/// resolved, and NULL otherwise. When @p Complain is true, this
11171/// routine will emit diagnostics if there is an error.
11172FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011173Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11174 QualType TargetType,
11175 bool Complain,
11176 DeclAccessPair &FoundResult,
11177 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011178 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011179
11180 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11181 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011182 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000011183 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000011184 bool ShouldComplain = Complain && !Resolver.hasComplained();
11185 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011186 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11187 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11188 else
11189 Resolver.ComplainNoMatchesFound();
11190 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000011191 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011192 Resolver.ComplainMultipleMatchesFound();
11193 else if (NumMatches == 1) {
11194 Fn = Resolver.getMatchingFunctionDecl();
11195 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000011196 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11197 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011198 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000011199 if (Complain) {
11200 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11201 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11202 else
11203 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11204 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000011205 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011206
11207 if (pHadMultipleCandidates)
11208 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011209 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011210}
11211
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011212/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011213/// resolve that function to a single function that can have its address taken.
11214/// This will modify `Pair` iff it returns non-null.
11215///
11216/// This routine can only realistically succeed if all but one candidates in the
11217/// overload set for SrcExpr cannot have their addresses taken.
11218FunctionDecl *
11219Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11220 DeclAccessPair &Pair) {
11221 OverloadExpr::FindResult R = OverloadExpr::find(E);
11222 OverloadExpr *Ovl = R.Expression;
11223 FunctionDecl *Result = nullptr;
11224 DeclAccessPair DAP;
11225 // Don't use the AddressOfResolver because we're specifically looking for
11226 // cases where we have one overload candidate that lacks
11227 // enable_if/pass_object_size/...
11228 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11229 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11230 if (!FD)
11231 return nullptr;
11232
11233 if (!checkAddressOfFunctionIsAvailable(FD))
11234 continue;
11235
11236 // We have more than one result; quit.
11237 if (Result)
11238 return nullptr;
11239 DAP = I.getPair();
11240 Result = FD;
11241 }
11242
11243 if (Result)
11244 Pair = DAP;
11245 return Result;
11246}
11247
George Burgess IVbeca4a32016-06-08 00:34:22 +000011248/// \brief Given an overloaded function, tries to turn it into a non-overloaded
11249/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11250/// will perform access checks, diagnose the use of the resultant decl, and, if
11251/// necessary, perform a function-to-pointer decay.
11252///
11253/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11254/// Otherwise, returns true. This may emit diagnostics and return true.
11255bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11256 ExprResult &SrcExpr) {
11257 Expr *E = SrcExpr.get();
11258 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11259
11260 DeclAccessPair DAP;
11261 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11262 if (!Found)
11263 return false;
11264
11265 // Emitting multiple diagnostics for a function that is both inaccessible and
11266 // unavailable is consistent with our behavior elsewhere. So, always check
11267 // for both.
11268 DiagnoseUseOfDecl(Found, E->getExprLoc());
11269 CheckAddressOfMemberAccess(E, DAP);
11270 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11271 if (Fixed->getType()->isFunctionType())
11272 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11273 else
11274 SrcExpr = Fixed;
11275 return true;
11276}
11277
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011278/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011279/// resolve that overloaded function expression down to a single function.
11280///
11281/// This routine can only resolve template-ids that refer to a single function
11282/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011283/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011284/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000011285///
11286/// If no template-ids are found, no diagnostics are emitted and NULL is
11287/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000011288FunctionDecl *
11289Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11290 bool Complain,
11291 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011292 // C++ [over.over]p1:
11293 // [...] [Note: any redundant set of parentheses surrounding the
11294 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011295 // C++ [over.over]p1:
11296 // [...] The overloaded function name can be preceded by the &
11297 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011298
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011299 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000011300 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000011301 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011302
11303 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011304 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011305 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011306
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011307 // Look through all of the overloaded functions, searching for one
11308 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011309 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011310 for (UnresolvedSetIterator I = ovl->decls_begin(),
11311 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011312 // C++0x [temp.arg.explicit]p3:
11313 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011314 // where deduction is not done, if a template argument list is
11315 // specified and it, along with any default template arguments,
11316 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011317 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011318 FunctionTemplateDecl *FunctionTemplate
11319 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011320
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011321 // C++ [over.over]p2:
11322 // If the name is a function template, template argument deduction is
11323 // done (14.8.2.2), and if the argument deduction succeeds, the
11324 // resulting template argument list is used to generate a single
11325 // function template specialization, which is added to the set of
11326 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011327 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011328 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011329 if (TemplateDeductionResult Result
11330 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011331 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011332 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011333 // Make a note of the failed deduction for diagnostics.
11334 // TODO: Actually use the failed-deduction info?
11335 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011336 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011337 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011338 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011339 }
11340
John McCall0009fcc2011-04-26 20:42:42 +000011341 assert(Specialization && "no specialization and no error?");
11342
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011343 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011344 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011345 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011346 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11347 << ovl->getName();
11348 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011349 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011350 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011351 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011352
John McCall0009fcc2011-04-26 20:42:42 +000011353 Matched = Specialization;
11354 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011355 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011356
Richard Smith9095e5b2016-11-01 01:31:23 +000011357 if (Matched &&
11358 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011359 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011360
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011361 return Matched;
11362}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011363
Douglas Gregor1beec452011-03-12 01:48:56 +000011364
11365
11366
John McCall50a2c2c2011-10-11 23:14:30 +000011367// Resolve and fix an overloaded expression that can be resolved
11368// because it identifies a single function template specialization.
11369//
Douglas Gregor1beec452011-03-12 01:48:56 +000011370// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011371//
11372// Return true if it was logically possible to so resolve the
11373// expression, regardless of whether or not it succeeded. Always
11374// returns true if 'complain' is set.
11375bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11376 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000011377 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000011378 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011379 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011380 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011381
John McCall50a2c2c2011-10-11 23:14:30 +000011382 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011383
John McCall0009fcc2011-04-26 20:42:42 +000011384 DeclAccessPair found;
11385 ExprResult SingleFunctionExpression;
11386 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11387 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011388 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011389 SrcExpr = ExprError();
11390 return true;
11391 }
John McCall0009fcc2011-04-26 20:42:42 +000011392
11393 // It is only correct to resolve to an instance method if we're
11394 // resolving a form that's permitted to be a pointer to member.
11395 // Otherwise we'll end up making a bound member expression, which
11396 // is illegal in all the contexts we resolve like this.
11397 if (!ovl.HasFormOfMemberPointer &&
11398 isa<CXXMethodDecl>(fn) &&
11399 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011400 if (!complain) return false;
11401
11402 Diag(ovl.Expression->getExprLoc(),
11403 diag::err_bound_member_function)
11404 << 0 << ovl.Expression->getSourceRange();
11405
11406 // TODO: I believe we only end up here if there's a mix of
11407 // static and non-static candidates (otherwise the expression
11408 // would have 'bound member' type, not 'overload' type).
11409 // Ideally we would note which candidate was chosen and why
11410 // the static candidates were rejected.
11411 SrcExpr = ExprError();
11412 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011413 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011414
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011415 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011416 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011417 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011418
11419 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011420 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011421 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011422 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011423 if (SingleFunctionExpression.isInvalid()) {
11424 SrcExpr = ExprError();
11425 return true;
11426 }
11427 }
John McCall0009fcc2011-04-26 20:42:42 +000011428 }
11429
11430 if (!SingleFunctionExpression.isUsable()) {
11431 if (complain) {
11432 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11433 << ovl.Expression->getName()
11434 << DestTypeForComplaining
11435 << OpRangeForComplaining
11436 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011437 NoteAllOverloadCandidates(SrcExpr.get());
11438
11439 SrcExpr = ExprError();
11440 return true;
11441 }
11442
11443 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011444 }
11445
John McCall50a2c2c2011-10-11 23:14:30 +000011446 SrcExpr = SingleFunctionExpression;
11447 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011448}
11449
Douglas Gregorcabea402009-09-22 15:41:20 +000011450/// \brief Add a single candidate to the overload set.
11451static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011452 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011453 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011454 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011455 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011456 bool PartialOverloading,
11457 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011458 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011459 if (isa<UsingShadowDecl>(Callee))
11460 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11461
Douglas Gregorcabea402009-09-22 15:41:20 +000011462 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011463 if (ExplicitTemplateArgs) {
11464 assert(!KnownValid && "Explicit template arguments?");
11465 return;
11466 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011467 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11468 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011469 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011470 return;
John McCalld14a8642009-11-21 08:51:07 +000011471 }
11472
11473 if (FunctionTemplateDecl *FuncTemplate
11474 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011475 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011476 ExplicitTemplateArgs, Args, CandidateSet,
11477 /*SuppressUsedConversions=*/false,
11478 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011479 return;
11480 }
11481
Richard Smith95ce4f62011-06-26 22:19:54 +000011482 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011483}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011484
Douglas Gregorcabea402009-09-22 15:41:20 +000011485/// \brief Add the overload candidates named by callee and/or found by argument
11486/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011487void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011488 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011489 OverloadCandidateSet &CandidateSet,
11490 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011491
11492#ifndef NDEBUG
11493 // Verify that ArgumentDependentLookup is consistent with the rules
11494 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011495 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011496 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11497 // and let Y be the lookup set produced by argument dependent
11498 // lookup (defined as follows). If X contains
11499 //
11500 // -- a declaration of a class member, or
11501 //
11502 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011503 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011504 //
11505 // -- a declaration that is neither a function or a function
11506 // template
11507 //
11508 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011509
John McCall57500772009-12-16 12:17:52 +000011510 if (ULE->requiresADL()) {
11511 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11512 E = ULE->decls_end(); I != E; ++I) {
11513 assert(!(*I)->getDeclContext()->isRecord());
11514 assert(isa<UsingShadowDecl>(*I) ||
11515 !(*I)->getDeclContext()->isFunctionOrMethod());
11516 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011517 }
11518 }
11519#endif
11520
John McCall57500772009-12-16 12:17:52 +000011521 // It would be nice to avoid this copy.
11522 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011523 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011524 if (ULE->hasExplicitTemplateArgs()) {
11525 ULE->copyTemplateArgumentsInto(TABuffer);
11526 ExplicitTemplateArgs = &TABuffer;
11527 }
11528
11529 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11530 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011531 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11532 CandidateSet, PartialOverloading,
11533 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011534
John McCall57500772009-12-16 12:17:52 +000011535 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011536 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011537 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011538 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011539}
John McCalld681c392009-12-16 08:11:27 +000011540
Richard Smith0603bbb2013-06-12 22:56:54 +000011541/// Determine whether a declaration with the specified name could be moved into
11542/// a different namespace.
11543static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11544 switch (Name.getCXXOverloadedOperator()) {
11545 case OO_New: case OO_Array_New:
11546 case OO_Delete: case OO_Array_Delete:
11547 return false;
11548
11549 default:
11550 return true;
11551 }
11552}
11553
Richard Smith998a5912011-06-05 22:42:48 +000011554/// Attempt to recover from an ill-formed use of a non-dependent name in a
11555/// template, where the non-dependent name was declared after the template
11556/// was defined. This is common in code written for a compilers which do not
11557/// correctly implement two-stage name lookup.
11558///
11559/// Returns true if a viable candidate was found and a diagnostic was issued.
11560static bool
11561DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11562 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011563 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011564 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011565 ArrayRef<Expr *> Args,
11566 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000011567 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11568 return false;
11569
11570 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011571 if (DC->isTransparentContext())
11572 continue;
11573
Richard Smith998a5912011-06-05 22:42:48 +000011574 SemaRef.LookupQualifiedName(R, DC);
11575
11576 if (!R.empty()) {
11577 R.suppressDiagnostics();
11578
11579 if (isa<CXXRecordDecl>(DC)) {
11580 // Don't diagnose names we find in classes; we get much better
11581 // diagnostics for these from DiagnoseEmptyLookup.
11582 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011583 if (DoDiagnoseEmptyLookup)
11584 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011585 return false;
11586 }
11587
Richard Smith100b24a2014-04-17 01:52:14 +000011588 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011589 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11590 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011591 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011592 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011593
11594 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011595 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011596 // No viable functions. Don't bother the user with notes for functions
11597 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011598 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011599 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011600 }
Richard Smith998a5912011-06-05 22:42:48 +000011601
11602 // Find the namespaces where ADL would have looked, and suggest
11603 // declaring the function there instead.
11604 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11605 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011606 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011607 AssociatedNamespaces,
11608 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011609 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011610 if (canBeDeclaredInNamespace(R.getLookupName())) {
11611 DeclContext *Std = SemaRef.getStdNamespace();
11612 for (Sema::AssociatedNamespaceSet::iterator
11613 it = AssociatedNamespaces.begin(),
11614 end = AssociatedNamespaces.end(); it != end; ++it) {
11615 // Never suggest declaring a function within namespace 'std'.
11616 if (Std && Std->Encloses(*it))
11617 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011618
Richard Smith0603bbb2013-06-12 22:56:54 +000011619 // Never suggest declaring a function within a namespace with a
11620 // reserved name, like __gnu_cxx.
11621 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11622 if (NS &&
11623 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11624 continue;
11625
11626 SuggestedNamespaces.insert(*it);
11627 }
Richard Smith998a5912011-06-05 22:42:48 +000011628 }
11629
11630 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11631 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011632 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011633 SemaRef.Diag(Best->Function->getLocation(),
11634 diag::note_not_found_by_two_phase_lookup)
11635 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011636 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011637 SemaRef.Diag(Best->Function->getLocation(),
11638 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011639 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011640 } else {
11641 // FIXME: It would be useful to list the associated namespaces here,
11642 // but the diagnostics infrastructure doesn't provide a way to produce
11643 // a localized representation of a list of items.
11644 SemaRef.Diag(Best->Function->getLocation(),
11645 diag::note_not_found_by_two_phase_lookup)
11646 << R.getLookupName() << 2;
11647 }
11648
11649 // Try to recover by calling this function.
11650 return true;
11651 }
11652
11653 R.clear();
11654 }
11655
11656 return false;
11657}
11658
11659/// Attempt to recover from ill-formed use of a non-dependent operator in a
11660/// template, where the non-dependent operator was declared after the template
11661/// was defined.
11662///
11663/// Returns true if a viable candidate was found and a diagnostic was issued.
11664static bool
11665DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11666 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011667 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011668 DeclarationName OpName =
11669 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11670 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11671 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011672 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011673 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011674}
11675
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011676namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011677class BuildRecoveryCallExprRAII {
11678 Sema &SemaRef;
11679public:
11680 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11681 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11682 SemaRef.IsBuildingRecoveryCallExpr = true;
11683 }
11684
11685 ~BuildRecoveryCallExprRAII() {
11686 SemaRef.IsBuildingRecoveryCallExpr = false;
11687 }
11688};
11689
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011690}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011691
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011692static std::unique_ptr<CorrectionCandidateCallback>
11693MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11694 bool HasTemplateArgs, bool AllowTypoCorrection) {
11695 if (!AllowTypoCorrection)
11696 return llvm::make_unique<NoTypoCorrectionCCC>();
11697 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11698 HasTemplateArgs, ME);
11699}
11700
John McCalld681c392009-12-16 08:11:27 +000011701/// Attempts to recover from a call where no functions were found.
11702///
11703/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011704static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011705BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011706 UnresolvedLookupExpr *ULE,
11707 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011708 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011709 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011710 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011711 // Do not try to recover if it is already building a recovery call.
11712 // This stops infinite loops for template instantiations like
11713 //
11714 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11715 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11716 //
11717 if (SemaRef.IsBuildingRecoveryCallExpr)
11718 return ExprError();
11719 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011720
11721 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011722 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011723 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011724
John McCall57500772009-12-16 12:17:52 +000011725 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011726 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011727 if (ULE->hasExplicitTemplateArgs()) {
11728 ULE->copyTemplateArgumentsInto(TABuffer);
11729 ExplicitTemplateArgs = &TABuffer;
11730 }
11731
John McCalld681c392009-12-16 08:11:27 +000011732 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11733 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011734 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011735 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011736 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011737 ExplicitTemplateArgs, Args,
11738 &DoDiagnoseEmptyLookup) &&
11739 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11740 S, SS, R,
11741 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11742 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11743 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011744 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011745
John McCall57500772009-12-16 12:17:52 +000011746 assert(!R.empty() && "lookup results empty despite recovery");
11747
Richard Smith151c4562016-12-20 21:35:28 +000011748 // If recovery created an ambiguity, just bail out.
11749 if (R.isAmbiguous()) {
11750 R.suppressDiagnostics();
11751 return ExprError();
11752 }
11753
John McCall57500772009-12-16 12:17:52 +000011754 // Build an implicit member call if appropriate. Just drop the
11755 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011756 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011757 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011758 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11759 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011760 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011761 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011762 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011763 else
11764 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11765
11766 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011767 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011768
11769 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011770 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011771 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011772 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011773 MultiExprArg(Args.data(), Args.size()),
11774 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011775}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011776
Sam Panzer0f384432012-08-21 00:52:01 +000011777/// \brief Constructs and populates an OverloadedCandidateSet from
11778/// the given function.
11779/// \returns true when an the ExprResult output parameter has been set.
11780bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11781 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011782 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011783 SourceLocation RParenLoc,
11784 OverloadCandidateSet *CandidateSet,
11785 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011786#ifndef NDEBUG
11787 if (ULE->requiresADL()) {
11788 // To do ADL, we must have found an unqualified name.
11789 assert(!ULE->getQualifier() && "qualified name with ADL");
11790
11791 // We don't perform ADL for implicit declarations of builtins.
11792 // Verify that this was correctly set up.
11793 FunctionDecl *F;
11794 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11795 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11796 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011797 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011798
John McCall57500772009-12-16 12:17:52 +000011799 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011800 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011801 }
John McCall57500772009-12-16 12:17:52 +000011802#endif
11803
John McCall4124c492011-10-17 18:40:02 +000011804 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011805 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011806 *Result = ExprError();
11807 return true;
11808 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011809
John McCall57500772009-12-16 12:17:52 +000011810 // Add the functions denoted by the callee to the set of candidate
11811 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011812 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011813
Hans Wennborgb2747382015-06-12 21:23:23 +000011814 if (getLangOpts().MSVCCompat &&
11815 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011816 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11817
11818 OverloadCandidateSet::iterator Best;
11819 if (CandidateSet->empty() ||
11820 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11821 OR_No_Viable_Function) {
11822 // In Microsoft mode, if we are inside a template class member function then
11823 // create a type dependent CallExpr. The goal is to postpone name lookup
11824 // to instantiation time to be able to search into type dependent base
11825 // classes.
11826 CallExpr *CE = new (Context) CallExpr(
11827 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011828 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011829 CE->setValueDependent(true);
11830 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011831 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011832 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011833 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011834 }
John McCalld681c392009-12-16 08:11:27 +000011835
Hans Wennborg64937c62015-06-11 21:21:57 +000011836 if (CandidateSet->empty())
11837 return false;
11838
John McCall4124c492011-10-17 18:40:02 +000011839 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011840 return false;
11841}
John McCall4124c492011-10-17 18:40:02 +000011842
Sam Panzer0f384432012-08-21 00:52:01 +000011843/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11844/// the completed call expression. If overload resolution fails, emits
11845/// diagnostics and returns ExprError()
11846static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11847 UnresolvedLookupExpr *ULE,
11848 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011849 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011850 SourceLocation RParenLoc,
11851 Expr *ExecConfig,
11852 OverloadCandidateSet *CandidateSet,
11853 OverloadCandidateSet::iterator *Best,
11854 OverloadingResult OverloadResult,
11855 bool AllowTypoCorrection) {
11856 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011857 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011858 RParenLoc, /*EmptyLookup=*/true,
11859 AllowTypoCorrection);
11860
11861 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011862 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011863 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011864 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011865 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11866 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011867 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011868 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11869 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011870 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011871
Richard Smith998a5912011-06-05 22:42:48 +000011872 case OR_No_Viable_Function: {
11873 // Try to recover by looking for viable functions which the user might
11874 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011875 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011876 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011877 /*EmptyLookup=*/false,
11878 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011879 if (!Recovery.isInvalid())
11880 return Recovery;
11881
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011882 // If the user passes in a function that we can't take the address of, we
11883 // generally end up emitting really bad error messages. Here, we attempt to
11884 // emit better ones.
11885 for (const Expr *Arg : Args) {
11886 if (!Arg->getType()->isFunctionType())
11887 continue;
11888 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11889 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11890 if (FD &&
11891 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11892 Arg->getExprLoc()))
11893 return ExprError();
11894 }
11895 }
11896
11897 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11898 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011899 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011900 break;
Richard Smith998a5912011-06-05 22:42:48 +000011901 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011902
11903 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011904 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011905 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011906 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011907 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011908
Sam Panzer0f384432012-08-21 00:52:01 +000011909 case OR_Deleted: {
11910 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11911 << (*Best)->Function->isDeleted()
11912 << ULE->getName()
11913 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11914 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011915 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011916
Sam Panzer0f384432012-08-21 00:52:01 +000011917 // We emitted an error for the unvailable/deleted function call but keep
11918 // the call in the AST.
11919 FunctionDecl *FDecl = (*Best)->Function;
11920 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011921 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11922 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011923 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011924 }
11925
Douglas Gregorb412e172010-07-25 18:17:45 +000011926 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011927 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011928}
11929
George Burgess IV7204ed92016-01-07 02:26:57 +000011930static void markUnaddressableCandidatesUnviable(Sema &S,
11931 OverloadCandidateSet &CS) {
11932 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11933 if (I->Viable &&
11934 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11935 I->Viable = false;
11936 I->FailureKind = ovl_fail_addr_not_available;
11937 }
11938 }
11939}
11940
Sam Panzer0f384432012-08-21 00:52:01 +000011941/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11942/// (which eventually refers to the declaration Func) and the call
11943/// arguments Args/NumArgs, attempt to resolve the function call down
11944/// to a specific function. If overload resolution succeeds, returns
11945/// the call expression produced by overload resolution.
11946/// Otherwise, emits diagnostics and returns ExprError.
11947ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11948 UnresolvedLookupExpr *ULE,
11949 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011950 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011951 SourceLocation RParenLoc,
11952 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011953 bool AllowTypoCorrection,
11954 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011955 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11956 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011957 ExprResult result;
11958
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011959 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11960 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011961 return result;
11962
George Burgess IV7204ed92016-01-07 02:26:57 +000011963 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11964 // functions that aren't addressible are considered unviable.
11965 if (CalleesAddressIsTaken)
11966 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11967
Sam Panzer0f384432012-08-21 00:52:01 +000011968 OverloadCandidateSet::iterator Best;
11969 OverloadingResult OverloadResult =
11970 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11971
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011972 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011973 RParenLoc, ExecConfig, &CandidateSet,
11974 &Best, OverloadResult,
11975 AllowTypoCorrection);
11976}
11977
John McCall4c4c1df2010-01-26 03:27:55 +000011978static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011979 return Functions.size() > 1 ||
11980 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11981}
11982
Douglas Gregor084d8552009-03-13 23:49:33 +000011983/// \brief Create a unary operation that may resolve to an overloaded
11984/// operator.
11985///
11986/// \param OpLoc The location of the operator itself (e.g., '*').
11987///
Craig Toppera92ffb02015-12-10 08:51:49 +000011988/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011989///
James Dennett18348b62012-06-22 08:52:37 +000011990/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011991/// considered by overload resolution. The caller needs to build this
11992/// set based on the context using, e.g.,
11993/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11994/// set should not contain any member functions; those will be added
11995/// by CreateOverloadedUnaryOp().
11996///
James Dennett91738ff2012-06-22 10:32:46 +000011997/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011998ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011999Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012000 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000012001 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012002 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12003 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12004 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012005 // TODO: provide better source location info.
12006 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000012007
John McCall4124c492011-10-17 18:40:02 +000012008 if (checkPlaceholderForOverload(*this, Input))
12009 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012010
Craig Topperc3ec1492014-05-26 06:22:03 +000012011 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000012012 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000012013
Douglas Gregor084d8552009-03-13 23:49:33 +000012014 // For post-increment and post-decrement, add the implicit '0' as
12015 // the second argument, so that we know this is a post-increment or
12016 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000012017 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012018 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000012019 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12020 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000012021 NumArgs = 2;
12022 }
12023
Richard Smithe54c3072013-05-05 15:51:06 +000012024 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12025
Douglas Gregor084d8552009-03-13 23:49:33 +000012026 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000012027 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012028 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12029 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012030
Craig Topperc3ec1492014-05-26 06:22:03 +000012031 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000012032 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012033 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012034 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012035 /*ADL*/ true, IsOverloaded(Fns),
12036 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012037 return new (Context)
12038 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12039 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000012040 }
12041
12042 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012043 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000012044
12045 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012046 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012047
12048 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012049 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012050
John McCall4c4c1df2010-01-26 03:27:55 +000012051 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000012052 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000012053 /*ExplicitTemplateArgs*/nullptr,
12054 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000012055
Douglas Gregor084d8552009-03-13 23:49:33 +000012056 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012057 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012058
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012059 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12060
Douglas Gregor084d8552009-03-13 23:49:33 +000012061 // Perform overload resolution.
12062 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012063 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012064 case OR_Success: {
12065 // We found a built-in operator or an overloaded operator.
12066 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000012067
Douglas Gregor084d8552009-03-13 23:49:33 +000012068 if (FnDecl) {
12069 // We matched an overloaded operator. Build a call to that
12070 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000012071
Douglas Gregor084d8552009-03-13 23:49:33 +000012072 // Convert the arguments.
12073 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012074 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012075
John Wiegley01296292011-04-08 18:41:53 +000012076 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012077 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012078 Best->FoundDecl, Method);
12079 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012080 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012081 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012082 } else {
12083 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012084 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000012085 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012086 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000012087 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012088 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000012089 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000012090 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012091 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012092 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012093 }
12094
Douglas Gregor084d8552009-03-13 23:49:33 +000012095 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000012096 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012097 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012098 if (FnExpr.isInvalid())
12099 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000012100
Richard Smithc1564702013-11-15 02:58:23 +000012101 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012102 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012103 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12104 ResultTy = ResultTy.getNonLValueExprType(Context);
12105
Eli Friedman030eee42009-11-18 03:58:17 +000012106 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000012107 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012108 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000012109 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000012110
Alp Toker314cc812014-01-25 16:55:45 +000012111 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000012112 return ExprError();
12113
John McCallb268a282010-08-23 23:25:46 +000012114 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000012115 } else {
12116 // We matched a built-in operator. Convert the arguments, then
12117 // break out so that we will build the appropriate built-in
12118 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012119 ExprResult InputRes =
12120 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
12121 Best->Conversions[0], AA_Passing);
12122 if (InputRes.isInvalid())
12123 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012124 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012125 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000012126 }
John Wiegley01296292011-04-08 18:41:53 +000012127 }
12128
12129 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000012130 // This is an erroneous use of an operator which can be overloaded by
12131 // a non-member function. Check for non-member operators which were
12132 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012133 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000012134 // FIXME: Recover by calling the found function.
12135 return ExprError();
12136
John Wiegley01296292011-04-08 18:41:53 +000012137 // No viable function; fall through to handling this as a
12138 // built-in operator, which will produce an error message for us.
12139 break;
12140
12141 case OR_Ambiguous:
12142 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12143 << UnaryOperator::getOpcodeStr(Opc)
12144 << Input->getType()
12145 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012146 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000012147 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12148 return ExprError();
12149
12150 case OR_Deleted:
12151 Diag(OpLoc, diag::err_ovl_deleted_oper)
12152 << Best->Function->isDeleted()
12153 << UnaryOperator::getOpcodeStr(Opc)
12154 << getDeletedOrUnavailableSuffix(Best->Function)
12155 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012156 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012157 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012158 return ExprError();
12159 }
Douglas Gregor084d8552009-03-13 23:49:33 +000012160
12161 // Either we found no viable overloaded operator or we matched a
12162 // built-in operator. In either case, fall through to trying to
12163 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000012164 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000012165}
12166
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012167/// \brief Create a binary operation that may resolve to an overloaded
12168/// operator.
12169///
12170/// \param OpLoc The location of the operator itself (e.g., '+').
12171///
Craig Toppera92ffb02015-12-10 08:51:49 +000012172/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012173///
James Dennett18348b62012-06-22 08:52:37 +000012174/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012175/// considered by overload resolution. The caller needs to build this
12176/// set based on the context using, e.g.,
12177/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12178/// set should not contain any member functions; those will be added
12179/// by CreateOverloadedBinOp().
12180///
12181/// \param LHS Left-hand argument.
12182/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000012183ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012184Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000012185 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012186 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012187 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012188 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000012189 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012190
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012191 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12192 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12193
12194 // If either side is type-dependent, create an appropriate dependent
12195 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000012196 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000012197 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012198 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000012199 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000012200 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012201 return new (Context) BinaryOperator(
12202 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12203 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012204
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012205 return new (Context) CompoundAssignOperator(
12206 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12207 Context.DependentTy, Context.DependentTy, OpLoc,
12208 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000012209 }
John McCall4c4c1df2010-01-26 03:27:55 +000012210
12211 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000012212 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012213 // TODO: provide better source location info in DNLoc component.
12214 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000012215 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000012216 = UnresolvedLookupExpr::Create(Context, NamingClass,
12217 NestedNameSpecifierLoc(), OpNameInfo,
12218 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012219 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012220 return new (Context)
12221 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12222 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012223 }
12224
John McCall4124c492011-10-17 18:40:02 +000012225 // Always do placeholder-like conversions on the RHS.
12226 if (checkPlaceholderForOverload(*this, Args[1]))
12227 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012228
John McCall526ab472011-10-25 17:37:35 +000012229 // Do placeholder-like conversion on the LHS; note that we should
12230 // not get here with a PseudoObject LHS.
12231 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000012232 if (checkPlaceholderForOverload(*this, Args[0]))
12233 return ExprError();
12234
Sebastian Redl6a96bf72009-11-18 23:10:33 +000012235 // If this is the assignment operator, we only perform overload resolution
12236 // if the left-hand side is a class or enumeration type. This is actually
12237 // a hack. The standard requires that we do overload resolution between the
12238 // various built-in candidates, but as DR507 points out, this can lead to
12239 // problems. So we do it this way, which pretty much follows what GCC does.
12240 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000012241 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000012242 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012243
John McCalle26a8722010-12-04 08:14:53 +000012244 // If this is the .* operator, which is not overloadable, just
12245 // create a built-in binary operator.
12246 if (Opc == BO_PtrMemD)
12247 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12248
Douglas Gregor084d8552009-03-13 23:49:33 +000012249 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012250 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012251
12252 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012253 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012254
12255 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012256 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012257
Richard Smith0daabd72014-09-23 20:31:39 +000012258 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12259 // performed for an assignment operator (nor for operator[] nor operator->,
12260 // which don't get here).
12261 if (Opc != BO_Assign)
12262 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12263 /*ExplicitTemplateArgs*/ nullptr,
12264 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000012265
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012266 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012267 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012268
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012269 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12270
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012271 // Perform overload resolution.
12272 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012273 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000012274 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012275 // We found a built-in operator or an overloaded operator.
12276 FunctionDecl *FnDecl = Best->Function;
12277
12278 if (FnDecl) {
12279 // We matched an overloaded operator. Build a call to that
12280 // operator.
12281
12282 // Convert the arguments.
12283 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000012284 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000012285 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012286
Chandler Carruth8e543b32010-12-12 08:17:55 +000012287 ExprResult Arg1 =
12288 PerformCopyInitialization(
12289 InitializedEntity::InitializeParameter(Context,
12290 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012291 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012292 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012293 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012294
John Wiegley01296292011-04-08 18:41:53 +000012295 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012296 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012297 Best->FoundDecl, Method);
12298 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012299 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012300 Args[0] = Arg0.getAs<Expr>();
12301 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012302 } else {
12303 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012304 ExprResult Arg0 = PerformCopyInitialization(
12305 InitializedEntity::InitializeParameter(Context,
12306 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012307 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012308 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012309 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012310
Chandler Carruth8e543b32010-12-12 08:17:55 +000012311 ExprResult Arg1 =
12312 PerformCopyInitialization(
12313 InitializedEntity::InitializeParameter(Context,
12314 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012315 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012316 if (Arg1.isInvalid())
12317 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012318 Args[0] = LHS = Arg0.getAs<Expr>();
12319 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012320 }
12321
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012322 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012323 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012324 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012325 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012326 if (FnExpr.isInvalid())
12327 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012328
Richard Smithc1564702013-11-15 02:58:23 +000012329 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012330 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012331 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12332 ResultTy = ResultTy.getNonLValueExprType(Context);
12333
John McCallb268a282010-08-23 23:25:46 +000012334 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012335 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012336 Args, ResultTy, VK, OpLoc,
12337 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012338
Alp Toker314cc812014-01-25 16:55:45 +000012339 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012340 FnDecl))
12341 return ExprError();
12342
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012343 ArrayRef<const Expr *> ArgsArray(Args, 2);
12344 // Cut off the implicit 'this'.
12345 if (isa<CXXMethodDecl>(FnDecl))
12346 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012347
12348 // Check for a self move.
12349 if (Op == OO_Equal)
12350 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12351
Douglas Gregorb4866e82015-06-19 18:13:19 +000012352 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012353 TheCall->getSourceRange(), VariadicDoesNotApply);
12354
John McCallb268a282010-08-23 23:25:46 +000012355 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012356 } else {
12357 // We matched a built-in operator. Convert the arguments, then
12358 // break out so that we will build the appropriate built-in
12359 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012360 ExprResult ArgsRes0 =
12361 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12362 Best->Conversions[0], AA_Passing);
12363 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012364 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012365 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012366
John Wiegley01296292011-04-08 18:41:53 +000012367 ExprResult ArgsRes1 =
12368 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12369 Best->Conversions[1], AA_Passing);
12370 if (ArgsRes1.isInvalid())
12371 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012372 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012373 break;
12374 }
12375 }
12376
Douglas Gregor66950a32009-09-30 21:46:01 +000012377 case OR_No_Viable_Function: {
12378 // C++ [over.match.oper]p9:
12379 // If the operator is the operator , [...] and there are no
12380 // viable functions, then the operator is assumed to be the
12381 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012382 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012383 break;
12384
Chandler Carruth8e543b32010-12-12 08:17:55 +000012385 // For class as left operand for assignment or compound assigment
12386 // operator do not fall through to handling in built-in, but report that
12387 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012388 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012389 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012390 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012391 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12392 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012393 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012394 if (Args[0]->getType()->isIncompleteType()) {
12395 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12396 << Args[0]->getType()
12397 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12398 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012399 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012400 // This is an erroneous use of an operator which can be overloaded by
12401 // a non-member function. Check for non-member operators which were
12402 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012403 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012404 // FIXME: Recover by calling the found function.
12405 return ExprError();
12406
Douglas Gregor66950a32009-09-30 21:46:01 +000012407 // No viable function; try to create a built-in operation, which will
12408 // produce an error. Then, show the non-viable candidates.
12409 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012411 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012412 "C++ binary operator overloading is missing candidates!");
12413 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012414 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012415 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012416 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012417 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012418
12419 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012420 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012421 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012422 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012423 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012424 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012425 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012426 return ExprError();
12427
12428 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012429 if (isImplicitlyDeleted(Best->Function)) {
12430 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12431 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012432 << Context.getRecordType(Method->getParent())
12433 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012434
Richard Smithde1a4872012-12-28 12:23:24 +000012435 // The user probably meant to call this special member. Just
12436 // explain why it's deleted.
12437 NoteDeletedFunction(Method);
12438 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012439 } else {
12440 Diag(OpLoc, diag::err_ovl_deleted_oper)
12441 << Best->Function->isDeleted()
12442 << BinaryOperator::getOpcodeStr(Opc)
12443 << getDeletedOrUnavailableSuffix(Best->Function)
12444 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12445 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012446 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012447 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012448 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012449 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012450
Douglas Gregor66950a32009-09-30 21:46:01 +000012451 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012452 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012453}
12454
John McCalldadc5752010-08-24 06:29:42 +000012455ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012456Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12457 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012458 Expr *Base, Expr *Idx) {
12459 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012460 DeclarationName OpName =
12461 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12462
12463 // If either side is type-dependent, create an appropriate dependent
12464 // expression.
12465 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12466
Craig Topperc3ec1492014-05-26 06:22:03 +000012467 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012468 // CHECKME: no 'operator' keyword?
12469 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12470 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012471 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012472 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012473 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012474 /*ADL*/ true, /*Overloaded*/ false,
12475 UnresolvedSetIterator(),
12476 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012477 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012478
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012479 return new (Context)
12480 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12481 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012482 }
12483
John McCall4124c492011-10-17 18:40:02 +000012484 // Handle placeholders on both operands.
12485 if (checkPlaceholderForOverload(*this, Args[0]))
12486 return ExprError();
12487 if (checkPlaceholderForOverload(*this, Args[1]))
12488 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012489
Sebastian Redladba46e2009-10-29 20:17:01 +000012490 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012491 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012492
12493 // Subscript can only be overloaded as a member function.
12494
12495 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012496 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012497
12498 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012499 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012500
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012501 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12502
Sebastian Redladba46e2009-10-29 20:17:01 +000012503 // Perform overload resolution.
12504 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012505 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012506 case OR_Success: {
12507 // We found a built-in operator or an overloaded operator.
12508 FunctionDecl *FnDecl = Best->Function;
12509
12510 if (FnDecl) {
12511 // We matched an overloaded operator. Build a call to that
12512 // operator.
12513
John McCalla0296f72010-03-19 07:35:19 +000012514 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012515
Sebastian Redladba46e2009-10-29 20:17:01 +000012516 // Convert the arguments.
12517 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012518 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012519 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012520 Best->FoundDecl, Method);
12521 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012522 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012523 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012524
Anders Carlssona68e51e2010-01-29 18:37:50 +000012525 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012526 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012527 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012528 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012529 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012530 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012531 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012532 if (InputInit.isInvalid())
12533 return ExprError();
12534
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012535 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012536
Sebastian Redladba46e2009-10-29 20:17:01 +000012537 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012538 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12539 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012540 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012541 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012542 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012543 OpLocInfo.getLoc(),
12544 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012545 if (FnExpr.isInvalid())
12546 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012547
Richard Smithc1564702013-11-15 02:58:23 +000012548 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012549 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012550 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12551 ResultTy = ResultTy.getNonLValueExprType(Context);
12552
John McCallb268a282010-08-23 23:25:46 +000012553 CXXOperatorCallExpr *TheCall =
12554 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012555 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012556 ResultTy, VK, RLoc,
12557 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012558
Alp Toker314cc812014-01-25 16:55:45 +000012559 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012560 return ExprError();
12561
John McCallb268a282010-08-23 23:25:46 +000012562 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012563 } else {
12564 // We matched a built-in operator. Convert the arguments, then
12565 // break out so that we will build the appropriate built-in
12566 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012567 ExprResult ArgsRes0 =
12568 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12569 Best->Conversions[0], AA_Passing);
12570 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012571 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012572 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012573
12574 ExprResult ArgsRes1 =
12575 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12576 Best->Conversions[1], AA_Passing);
12577 if (ArgsRes1.isInvalid())
12578 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012579 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012580
12581 break;
12582 }
12583 }
12584
12585 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012586 if (CandidateSet.empty())
12587 Diag(LLoc, diag::err_ovl_no_oper)
12588 << Args[0]->getType() << /*subscript*/ 0
12589 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12590 else
12591 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12592 << Args[0]->getType()
12593 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012594 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012595 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012596 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012597 }
12598
12599 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012600 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012601 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012602 << Args[0]->getType() << Args[1]->getType()
12603 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012604 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012605 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012606 return ExprError();
12607
12608 case OR_Deleted:
12609 Diag(LLoc, diag::err_ovl_deleted_oper)
12610 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012611 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012612 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012613 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012614 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012615 return ExprError();
12616 }
12617
12618 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012619 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012620}
12621
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012622/// BuildCallToMemberFunction - Build a call to a member
12623/// function. MemExpr is the expression that refers to the member
12624/// function (and includes the object parameter), Args/NumArgs are the
12625/// arguments to the function call (not including the object
12626/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012627/// expression refers to a non-static member function or an overloaded
12628/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012629ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012630Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012631 SourceLocation LParenLoc,
12632 MultiExprArg Args,
12633 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012634 assert(MemExprE->getType() == Context.BoundMemberTy ||
12635 MemExprE->getType() == Context.OverloadTy);
12636
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012637 // Dig out the member expression. This holds both the object
12638 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012639 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012640
John McCall0009fcc2011-04-26 20:42:42 +000012641 // Determine whether this is a call to a pointer-to-member function.
12642 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12643 assert(op->getType() == Context.BoundMemberTy);
12644 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12645
12646 QualType fnType =
12647 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12648
12649 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12650 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012651 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012652
12653 // Check that the object type isn't more qualified than the
12654 // member function we're calling.
12655 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12656
12657 QualType objectType = op->getLHS()->getType();
12658 if (op->getOpcode() == BO_PtrMemI)
12659 objectType = objectType->castAs<PointerType>()->getPointeeType();
12660 Qualifiers objectQuals = objectType.getQualifiers();
12661
12662 Qualifiers difference = objectQuals - funcQuals;
12663 difference.removeObjCGCAttr();
12664 difference.removeAddressSpace();
12665 if (difference) {
12666 std::string qualsString = difference.getAsString();
12667 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12668 << fnType.getUnqualifiedType()
12669 << qualsString
12670 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12671 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012672
John McCall0009fcc2011-04-26 20:42:42 +000012673 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012674 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012675 resultType, valueKind, RParenLoc);
12676
Alp Toker314cc812014-01-25 16:55:45 +000012677 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012678 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012679 return ExprError();
12680
Craig Topperc3ec1492014-05-26 06:22:03 +000012681 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012682 return ExprError();
12683
Richard Trieu9be9c682013-06-22 02:30:38 +000012684 if (CheckOtherCall(call, proto))
12685 return ExprError();
12686
John McCall0009fcc2011-04-26 20:42:42 +000012687 return MaybeBindToTemporary(call);
12688 }
12689
David Majnemerced8bdf2015-02-25 17:36:15 +000012690 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12691 return new (Context)
12692 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12693
John McCall4124c492011-10-17 18:40:02 +000012694 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012695 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012696 return ExprError();
12697
John McCall10eae182009-11-30 22:42:35 +000012698 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012699 CXXMethodDecl *Method = nullptr;
12700 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12701 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012702 if (isa<MemberExpr>(NakedMemExpr)) {
12703 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012704 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012705 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012706 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012707 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012708 } else {
12709 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012710 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012711
John McCall6e9f8f62009-12-03 04:06:58 +000012712 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012713 Expr::Classification ObjectClassification
12714 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12715 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012716
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012717 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012718 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12719 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012720
John McCall2d74de92009-12-01 22:10:20 +000012721 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012722 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012723 if (UnresExpr->hasExplicitTemplateArgs()) {
12724 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12725 TemplateArgs = &TemplateArgsBuffer;
12726 }
12727
George Burgess IV177399e2017-01-09 04:12:14 +000012728 // Poor-programmer's Lazy<Expr *>; isImplicitAccess requires stripping
12729 // parens/casts, which would be nice to avoid potentially doing multiple
12730 // times.
12731 llvm::Optional<Expr *> UnresolvedBase;
12732 auto GetUnresolvedBase = [&] {
12733 if (!UnresolvedBase.hasValue())
12734 UnresolvedBase =
12735 UnresExpr->isImplicitAccess() ? nullptr : UnresExpr->getBase();
12736 return *UnresolvedBase;
12737 };
John McCall10eae182009-11-30 22:42:35 +000012738 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12739 E = UnresExpr->decls_end(); I != E; ++I) {
12740
John McCall6e9f8f62009-12-03 04:06:58 +000012741 NamedDecl *Func = *I;
12742 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12743 if (isa<UsingShadowDecl>(Func))
12744 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12745
Douglas Gregor02824322011-01-26 19:30:28 +000012746
Francois Pichet64225792011-01-18 05:04:39 +000012747 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012748 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012749 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012750 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012751 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012752 // If explicit template arguments were provided, we can't call a
12753 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012754 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012755 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012756
John McCalla0296f72010-03-19 07:35:19 +000012757 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
George Burgess IV177399e2017-01-09 04:12:14 +000012758 ObjectClassification,
12759 /*ThisArg=*/GetUnresolvedBase(), Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012760 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012761 } else {
George Burgess IV177399e2017-01-09 04:12:14 +000012762 AddMethodTemplateCandidate(
12763 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12764 TemplateArgs, ObjectType, ObjectClassification,
12765 /*ThisArg=*/GetUnresolvedBase(), Args, CandidateSet,
12766 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012767 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012768 }
Mike Stump11289f42009-09-09 15:08:12 +000012769
John McCall10eae182009-11-30 22:42:35 +000012770 DeclarationName DeclName = UnresExpr->getMemberName();
12771
John McCall4124c492011-10-17 18:40:02 +000012772 UnbridgedCasts.restore();
12773
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012774 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012775 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012776 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012777 case OR_Success:
12778 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012779 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012780 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012781 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12782 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012783 // If FoundDecl is different from Method (such as if one is a template
12784 // and the other a specialization), make sure DiagnoseUseOfDecl is
12785 // called on both.
12786 // FIXME: This would be more comprehensively addressed by modifying
12787 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12788 // being used.
12789 if (Method != FoundDecl.getDecl() &&
12790 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12791 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012792 break;
12793
12794 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012795 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012796 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012797 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012798 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012799 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012800 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012801
12802 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012803 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012804 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012805 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012806 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012807 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012808
12809 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012810 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012811 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012812 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012813 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012814 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012815 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012816 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012817 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012818 }
12819
John McCall16df1e52010-03-30 21:47:33 +000012820 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012821
John McCall2d74de92009-12-01 22:10:20 +000012822 // If overload resolution picked a static member, build a
12823 // non-member call based on that function.
12824 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012825 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12826 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012827 }
12828
John McCall10eae182009-11-30 22:42:35 +000012829 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012830 }
12831
Alp Toker314cc812014-01-25 16:55:45 +000012832 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012833 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12834 ResultType = ResultType.getNonLValueExprType(Context);
12835
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012836 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012837 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012838 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012839 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012840
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012841 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012842 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012843 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012844 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012845
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012846 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012847 // We only need to do this if there was actually an overload; otherwise
12848 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012849 if (!Method->isStatic()) {
12850 ExprResult ObjectArg =
12851 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12852 FoundDecl, Method);
12853 if (ObjectArg.isInvalid())
12854 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012855 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012856 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012857
12858 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012859 const FunctionProtoType *Proto =
12860 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012861 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012862 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012863 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012864
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012865 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012866
Richard Smith55ce3522012-06-25 20:30:08 +000012867 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012868 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012869
George Burgess IVaea6ade2015-09-25 17:53:16 +000012870 // In the case the method to call was not selected by the overloading
12871 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012872 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000012873 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000012874 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000012875 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000012876 diag::err_ovl_no_viable_member_function_in_call)
12877 << Method << Method->getSourceRange();
12878 Diag(Method->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000012879 diag::note_ovl_candidate_disabled_by_function_cond_attr)
George Burgess IVaea6ade2015-09-25 17:53:16 +000012880 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12881 return ExprError();
12882 }
George Burgess IV177399e2017-01-09 04:12:14 +000012883
12884 SmallVector<DiagnoseIfAttr *, 4> Nonfatal;
12885 if (const DiagnoseIfAttr *Attr = checkArgDependentDiagnoseIf(
12886 Method, Args, Nonfatal, false, MemE->getBase())) {
12887 emitDiagnoseIfDiagnostic(MemE->getMemberLoc(), Attr);
12888 return ExprError();
12889 }
12890
12891 for (const auto *Attr : Nonfatal)
12892 emitDiagnoseIfDiagnostic(MemE->getMemberLoc(), Attr);
George Burgess IVaea6ade2015-09-25 17:53:16 +000012893 }
12894
Anders Carlsson47061ee2011-05-06 14:25:31 +000012895 if ((isa<CXXConstructorDecl>(CurContext) ||
12896 isa<CXXDestructorDecl>(CurContext)) &&
12897 TheCall->getMethodDecl()->isPure()) {
12898 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12899
Davide Italianoccb37382015-07-14 23:36:10 +000012900 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12901 MemExpr->performsVirtualDispatch(getLangOpts())) {
12902 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012903 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12904 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12905 << MD->getParent()->getDeclName();
12906
12907 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012908 if (getLangOpts().AppleKext)
12909 Diag(MemExpr->getLocStart(),
12910 diag::note_pure_qualified_call_kext)
12911 << MD->getParent()->getDeclName()
12912 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012913 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012914 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012915
12916 if (CXXDestructorDecl *DD =
12917 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12918 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012919 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012920 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12921 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12922 MemExpr->getMemberLoc());
12923 }
12924
John McCallb268a282010-08-23 23:25:46 +000012925 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012926}
12927
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012928/// BuildCallToObjectOfClassType - Build a call to an object of class
12929/// type (C++ [over.call.object]), which can end up invoking an
12930/// overloaded function call operator (@c operator()) or performing a
12931/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012932ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012933Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012934 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012935 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012936 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012937 if (checkPlaceholderForOverload(*this, Obj))
12938 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012939 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012940
12941 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012942 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012943 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012944
Nico Weberb58e51c2014-11-19 05:21:39 +000012945 assert(Object.get()->getType()->isRecordType() &&
12946 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012947 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012948
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012949 // C++ [over.call.object]p1:
12950 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012951 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012952 // candidate functions includes at least the function call
12953 // operators of T. The function call operators of T are obtained by
12954 // ordinary lookup of the name operator() in the context of
12955 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012956 OverloadCandidateSet CandidateSet(LParenLoc,
12957 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012958 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012959
John Wiegley01296292011-04-08 18:41:53 +000012960 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012961 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012962 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012963
John McCall27b18f82009-11-17 02:14:36 +000012964 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12965 LookupQualifiedName(R, Record->getDecl());
12966 R.suppressDiagnostics();
12967
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012968 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012969 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012970 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012971 Object.get()->Classify(Context),
George Burgess IV177399e2017-01-09 04:12:14 +000012972 Object.get(), Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012973 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012974 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012975
Douglas Gregorab7897a2008-11-19 22:57:39 +000012976 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012977 // In addition, for each (non-explicit in C++0x) conversion function
12978 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012979 //
12980 // operator conversion-type-id () cv-qualifier;
12981 //
12982 // where cv-qualifier is the same cv-qualification as, or a
12983 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012984 // denotes the type "pointer to function of (P1,...,Pn) returning
12985 // R", or the type "reference to pointer to function of
12986 // (P1,...,Pn) returning R", or the type "reference to function
12987 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012988 // is also considered as a candidate function. Similarly,
12989 // surrogate call functions are added to the set of candidate
12990 // functions for each conversion function declared in an
12991 // accessible base class provided the function is not hidden
12992 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012993 const auto &Conversions =
12994 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12995 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012996 NamedDecl *D = *I;
12997 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12998 if (isa<UsingShadowDecl>(D))
12999 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013000
Douglas Gregor74ba25c2009-10-21 06:18:39 +000013001 // Skip over templated conversion functions; they aren't
13002 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000013003 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000013004 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000013005
John McCall6e9f8f62009-12-03 04:06:58 +000013006 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013007 if (!Conv->isExplicit()) {
13008 // Strip the reference type (if any) and then the pointer type (if
13009 // any) to get down to what might be a function type.
13010 QualType ConvType = Conv->getConversionType().getNonReferenceType();
13011 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13012 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000013013
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013014 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13015 {
13016 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013017 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000013018 }
13019 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000013020 }
Mike Stump11289f42009-09-09 15:08:12 +000013021
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013022 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13023
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013024 // Perform overload resolution.
13025 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000013026 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000013027 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013028 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000013029 // Overload resolution succeeded; we'll build the appropriate call
13030 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013031 break;
13032
13033 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000013034 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013035 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000013036 << Object.get()->getType() << /*call*/ 1
13037 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000013038 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013039 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000013040 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000013041 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013042 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013043 break;
13044
13045 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013046 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013047 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000013048 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013049 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013050 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000013051
13052 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013053 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000013054 diag::err_ovl_deleted_object_call)
13055 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000013056 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013057 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000013058 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013059 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000013060 break;
Mike Stump11289f42009-09-09 15:08:12 +000013061 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013062
Douglas Gregorb412e172010-07-25 18:17:45 +000013063 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013064 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013065
John McCall4124c492011-10-17 18:40:02 +000013066 UnbridgedCasts.restore();
13067
Craig Topperc3ec1492014-05-26 06:22:03 +000013068 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000013069 // Since there is no function declaration, this is one of the
13070 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000013071 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000013072 = cast<CXXConversionDecl>(
13073 Best->Conversions[0].UserDefined.ConversionFunction);
13074
Craig Topperc3ec1492014-05-26 06:22:03 +000013075 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13076 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000013077 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13078 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000013079 assert(Conv == Best->FoundDecl.getDecl() &&
13080 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000013081 // We selected one of the surrogate functions that converts the
13082 // object parameter to a function pointer. Perform the conversion
13083 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013084
Fariborz Jahanian774cf792009-09-28 18:35:46 +000013085 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000013086 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013087 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13088 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000013089 if (Call.isInvalid())
13090 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000013091 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013092 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13093 CK_UserDefinedConversion, Call.get(),
13094 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013095
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013096 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000013097 }
13098
Craig Topperc3ec1492014-05-26 06:22:03 +000013099 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000013100
Douglas Gregorab7897a2008-11-19 22:57:39 +000013101 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13102 // that calls this method, using Object for the implicit object
13103 // parameter and passing along the remaining arguments.
13104 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000013105
13106 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000013107 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000013108 return ExprError();
13109
Chandler Carruth8e543b32010-12-12 08:17:55 +000013110 const FunctionProtoType *Proto =
13111 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013112
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013113 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000013114
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013115 DeclarationNameInfo OpLocInfo(
13116 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13117 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000013118 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013119 HadMultipleCandidates,
13120 OpLocInfo.getLoc(),
13121 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000013122 if (NewFn.isInvalid())
13123 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013124
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013125 // Build the full argument list for the method call (the implicit object
13126 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000013127 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013128 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000013129 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013130
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013131 // Once we've built TheCall, all of the expressions are properly
13132 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000013133 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013134 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13135 ResultTy = ResultTy.getNonLValueExprType(Context);
13136
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013137 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000013138 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13139 VK, RParenLoc, false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013140
Alp Toker314cc812014-01-25 16:55:45 +000013141 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000013142 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013143
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013144 // We may have default arguments. If so, we need to allocate more
13145 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013146 if (Args.size() < NumParams)
13147 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013148
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013149 bool IsError = false;
13150
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013151 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000013152 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000013153 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013154 Best->FoundDecl, Method);
13155 if (ObjRes.isInvalid())
13156 IsError = true;
13157 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013158 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013159 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013160
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013161 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013162 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013163 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013164 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013165 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000013166
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013167 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013168
John McCalldadc5752010-08-24 06:29:42 +000013169 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013170 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000013171 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013172 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000013173 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013174
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013175 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013176 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013177 } else {
John McCalldadc5752010-08-24 06:29:42 +000013178 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000013179 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13180 if (DefArg.isInvalid()) {
13181 IsError = true;
13182 break;
13183 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013184
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013185 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013186 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013187
13188 TheCall->setArg(i + 1, Arg);
13189 }
13190
13191 // If this is a variadic call, handle args passed through "...".
13192 if (Proto->isVariadic()) {
13193 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013194 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013195 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13196 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000013197 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013198 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013199 }
13200 }
13201
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013202 if (IsError) return true;
13203
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013204 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000013205
Richard Smith55ce3522012-06-25 20:30:08 +000013206 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000013207 return true;
13208
John McCalle172be52010-08-24 06:09:16 +000013209 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013210}
13211
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013212/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000013213/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013214/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000013215ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013216Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13217 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000013218 assert(Base->getType()->isRecordType() &&
13219 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000013220
John McCall4124c492011-10-17 18:40:02 +000013221 if (checkPlaceholderForOverload(*this, Base))
13222 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000013223
John McCallbc077cf2010-02-08 23:07:23 +000013224 SourceLocation Loc = Base->getExprLoc();
13225
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013226 // C++ [over.ref]p1:
13227 //
13228 // [...] An expression x->m is interpreted as (x.operator->())->m
13229 // for a class object x of type T if T::operator->() exists and if
13230 // the operator is selected as the best match function by the
13231 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000013232 DeclarationName OpName =
13233 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000013234 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013235 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000013236
John McCallbc077cf2010-02-08 23:07:23 +000013237 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013238 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000013239 return ExprError();
13240
John McCall27b18f82009-11-17 02:14:36 +000013241 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13242 LookupQualifiedName(R, BaseRecord->getDecl());
13243 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000013244
13245 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000013246 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000013247 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
George Burgess IV177399e2017-01-09 04:12:14 +000013248 Base, None, CandidateSet,
13249 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000013250 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013251
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013252 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13253
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013254 // Perform overload resolution.
13255 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000013256 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013257 case OR_Success:
13258 // Overload resolution succeeded; we'll build the call below.
13259 break;
13260
13261 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013262 if (CandidateSet.empty()) {
13263 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013264 if (NoArrowOperatorFound) {
13265 // Report this specific error to the caller instead of emitting a
13266 // diagnostic, as requested.
13267 *NoArrowOperatorFound = true;
13268 return ExprError();
13269 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013270 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13271 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013272 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013273 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013274 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013275 }
13276 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013277 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000013278 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013279 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013280 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013281
13282 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000013283 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13284 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013285 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013286 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000013287
13288 case OR_Deleted:
13289 Diag(OpLoc, diag::err_ovl_deleted_oper)
13290 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013291 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013292 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013293 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013294 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013295 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013296 }
13297
Craig Topperc3ec1492014-05-26 06:22:03 +000013298 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000013299
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013300 // Convert the object parameter.
13301 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000013302 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000013303 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013304 Best->FoundDecl, Method);
13305 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000013306 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013307 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000013308
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013309 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000013310 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013311 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000013312 if (FnExpr.isInvalid())
13313 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013314
Alp Toker314cc812014-01-25 16:55:45 +000013315 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013316 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13317 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000013318 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013319 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000013320 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013321
Alp Toker314cc812014-01-25 16:55:45 +000013322 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013323 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013324
13325 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013326}
13327
Richard Smithbcc22fc2012-03-09 08:00:36 +000013328/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13329/// a literal operator described by the provided lookup results.
13330ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13331 DeclarationNameInfo &SuffixInfo,
13332 ArrayRef<Expr*> Args,
13333 SourceLocation LitEndLoc,
13334 TemplateArgumentListInfo *TemplateArgs) {
13335 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013336
Richard Smith100b24a2014-04-17 01:52:14 +000013337 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13338 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013339 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13340 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013341
Richard Smithbcc22fc2012-03-09 08:00:36 +000013342 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13343
Richard Smithbcc22fc2012-03-09 08:00:36 +000013344 // Perform overload resolution. This will usually be trivial, but might need
13345 // to perform substitutions for a literal operator template.
13346 OverloadCandidateSet::iterator Best;
13347 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13348 case OR_Success:
13349 case OR_Deleted:
13350 break;
13351
13352 case OR_No_Viable_Function:
13353 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13354 << R.getLookupName();
13355 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13356 return ExprError();
13357
13358 case OR_Ambiguous:
13359 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13360 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13361 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013362 }
13363
Richard Smithbcc22fc2012-03-09 08:00:36 +000013364 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013365 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13366 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013367 SuffixInfo.getLoc(),
13368 SuffixInfo.getInfo());
13369 if (Fn.isInvalid())
13370 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013371
13372 // Check the argument types. This should almost always be a no-op, except
13373 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013374 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013375 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013376 ExprResult InputInit = PerformCopyInitialization(
13377 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13378 SourceLocation(), Args[ArgIdx]);
13379 if (InputInit.isInvalid())
13380 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013381 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013382 }
13383
Alp Toker314cc812014-01-25 16:55:45 +000013384 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013385 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13386 ResultTy = ResultTy.getNonLValueExprType(Context);
13387
Richard Smithc67fdd42012-03-07 08:35:16 +000013388 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013389 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013390 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013391 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13392
Alp Toker314cc812014-01-25 16:55:45 +000013393 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013394 return ExprError();
13395
Craig Topperc3ec1492014-05-26 06:22:03 +000013396 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013397 return ExprError();
13398
13399 return MaybeBindToTemporary(UDL);
13400}
13401
Sam Panzer0f384432012-08-21 00:52:01 +000013402/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13403/// given LookupResult is non-empty, it is assumed to describe a member which
13404/// will be invoked. Otherwise, the function will be found via argument
13405/// dependent lookup.
13406/// CallExpr is set to a valid expression and FRS_Success returned on success,
13407/// otherwise CallExpr is set to ExprError() and some non-success value
13408/// is returned.
13409Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013410Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13411 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013412 const DeclarationNameInfo &NameInfo,
13413 LookupResult &MemberLookup,
13414 OverloadCandidateSet *CandidateSet,
13415 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013416 Scope *S = nullptr;
13417
Sam Panzer0f384432012-08-21 00:52:01 +000013418 CandidateSet->clear();
13419 if (!MemberLookup.empty()) {
13420 ExprResult MemberRef =
13421 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13422 /*IsPtr=*/false, CXXScopeSpec(),
13423 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013424 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013425 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013426 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013427 if (MemberRef.isInvalid()) {
13428 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013429 return FRS_DiagnosticIssued;
13430 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013431 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013432 if (CallExpr->isInvalid()) {
13433 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013434 return FRS_DiagnosticIssued;
13435 }
13436 } else {
13437 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013438 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013439 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013440 NestedNameSpecifierLoc(), NameInfo,
13441 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013442 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013443
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013444 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013445 CandidateSet, CallExpr);
13446 if (CandidateSet->empty() || CandidateSetError) {
13447 *CallExpr = ExprError();
13448 return FRS_NoViableFunction;
13449 }
13450 OverloadCandidateSet::iterator Best;
13451 OverloadingResult OverloadResult =
13452 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13453
13454 if (OverloadResult == OR_No_Viable_Function) {
13455 *CallExpr = ExprError();
13456 return FRS_NoViableFunction;
13457 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013458 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013459 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013460 OverloadResult,
13461 /*AllowTypoCorrection=*/false);
13462 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13463 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013464 return FRS_DiagnosticIssued;
13465 }
13466 }
13467 return FRS_Success;
13468}
13469
13470
Douglas Gregorcd695e52008-11-10 20:40:00 +000013471/// FixOverloadedFunctionReference - E is an expression that refers to
13472/// a C++ overloaded function (possibly with some parentheses and
13473/// perhaps a '&' around it). We have resolved the overloaded function
13474/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013475/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013476Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013477 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013478 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013479 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13480 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013481 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013482 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013483
Douglas Gregor51c538b2009-11-20 19:42:02 +000013484 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013485 }
13486
Douglas Gregor51c538b2009-11-20 19:42:02 +000013487 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013488 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13489 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013490 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013491 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013492 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013493 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013494 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013495 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013496
13497 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013498 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013499 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013500 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013501 }
13502
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013503 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13504 if (!GSE->isResultDependent()) {
13505 Expr *SubExpr =
13506 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13507 if (SubExpr == GSE->getResultExpr())
13508 return GSE;
13509
13510 // Replace the resulting type information before rebuilding the generic
13511 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013512 ArrayRef<Expr *> A = GSE->getAssocExprs();
13513 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013514 unsigned ResultIdx = GSE->getResultIndex();
13515 AssocExprs[ResultIdx] = SubExpr;
13516
13517 return new (Context) GenericSelectionExpr(
13518 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13519 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13520 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13521 ResultIdx);
13522 }
13523 // Rather than fall through to the unreachable, return the original generic
13524 // selection expression.
13525 return GSE;
13526 }
13527
Douglas Gregor51c538b2009-11-20 19:42:02 +000013528 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013529 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013530 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013531 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13532 if (Method->isStatic()) {
13533 // Do nothing: static member functions aren't any different
13534 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013535 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013536 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013537 // UnresolvedLookupExpr holding an overloaded member function
13538 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013539 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13540 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013541 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013542 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013543
John McCalld14a8642009-11-21 08:51:07 +000013544 assert(isa<DeclRefExpr>(SubExpr)
13545 && "fixed to something other than a decl ref");
13546 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13547 && "fixed to a member ref with no nested name qualifier");
13548
13549 // We have taken the address of a pointer to member
13550 // function. Perform the computation here so that we get the
13551 // appropriate pointer to member type.
13552 QualType ClassType
13553 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13554 QualType MemPtrType
13555 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013556 // Under the MS ABI, lock down the inheritance model now.
13557 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13558 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013559
John McCall7decc9e2010-11-18 06:31:45 +000013560 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13561 VK_RValue, OK_Ordinary,
13562 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013563 }
13564 }
John McCall16df1e52010-03-30 21:47:33 +000013565 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13566 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013567 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013568 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013569
John McCalle3027922010-08-25 11:45:40 +000013570 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013571 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013572 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013573 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013574 }
John McCalld14a8642009-11-21 08:51:07 +000013575
Richard Smith84a0b6d2016-10-18 23:39:12 +000013576 // C++ [except.spec]p17:
13577 // An exception-specification is considered to be needed when:
13578 // - in an expression the function is the unique lookup result or the
13579 // selected member of a set of overloaded functions
13580 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13581 ResolveExceptionSpec(E->getExprLoc(), FPT);
13582
John McCalld14a8642009-11-21 08:51:07 +000013583 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013584 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013585 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013586 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013587 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13588 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013589 }
13590
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013591 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13592 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013593 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013594 Fn,
John McCall113bee02012-03-10 09:33:50 +000013595 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013596 ULE->getNameLoc(),
13597 Fn->getType(),
13598 VK_LValue,
13599 Found.getDecl(),
13600 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013601 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013602 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13603 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013604 }
13605
John McCall10eae182009-11-30 22:42:35 +000013606 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013607 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013608 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013609 if (MemExpr->hasExplicitTemplateArgs()) {
13610 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13611 TemplateArgs = &TemplateArgsBuffer;
13612 }
John McCall6b51f282009-11-23 01:53:49 +000013613
John McCall2d74de92009-12-01 22:10:20 +000013614 Expr *Base;
13615
John McCall7decc9e2010-11-18 06:31:45 +000013616 // If we're filling in a static method where we used to have an
13617 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013618 if (MemExpr->isImplicitAccess()) {
13619 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013620 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13621 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013622 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013623 Fn,
John McCall113bee02012-03-10 09:33:50 +000013624 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013625 MemExpr->getMemberLoc(),
13626 Fn->getType(),
13627 VK_LValue,
13628 Found.getDecl(),
13629 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013630 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013631 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13632 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013633 } else {
13634 SourceLocation Loc = MemExpr->getMemberLoc();
13635 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013636 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013637 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013638 Base = new (Context) CXXThisExpr(Loc,
13639 MemExpr->getBaseType(),
13640 /*isImplicit=*/true);
13641 }
John McCall2d74de92009-12-01 22:10:20 +000013642 } else
John McCallc3007a22010-10-26 07:05:15 +000013643 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013644
John McCall4adb38c2011-04-27 00:36:17 +000013645 ExprValueKind valueKind;
13646 QualType type;
13647 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13648 valueKind = VK_LValue;
13649 type = Fn->getType();
13650 } else {
13651 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013652 type = Context.BoundMemberTy;
13653 }
13654
13655 MemberExpr *ME = MemberExpr::Create(
13656 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13657 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13658 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13659 OK_Ordinary);
13660 ME->setHadMultipleCandidates(true);
13661 MarkMemberReferenced(ME);
13662 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013664
John McCallc3007a22010-10-26 07:05:15 +000013665 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013666}
13667
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013668ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013669 DeclAccessPair Found,
13670 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013671 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013672}