blob: c556fb7e43b5772b7b3802523d6fd045cdad7d7b [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,
Egor Churaevc217f372017-03-21 12:55:55 +0000134 ICR_OCL_Scalar_Widening,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000135 ICR_Complex_Real_Conversion,
136 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000137 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000138 ICR_Writeback_Conversion,
139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140 // it was omitted by the patch that added
141 // ICK_Zero_Event_Conversion
George Burgess IV2099b542016-09-02 22:59:57 +0000142 ICR_C_Conversion,
143 ICR_C_Conversion_Extension
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000144 };
145 return Rank[(int)Kind];
146}
147
148/// GetImplicitConversionName - Return the name of this kind of
149/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000150static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 "No conversion",
153 "Lvalue-to-rvalue",
154 "Array-to-pointer",
155 "Function-to-pointer",
Richard Smith3c4f8d22016-10-16 17:54:23 +0000156 "Function pointer conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000157 "Qualification",
158 "Integral promotion",
159 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000160 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000161 "Integral conversion",
162 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000163 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000164 "Floating-integral conversion",
165 "Pointer conversion",
166 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000167 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000168 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000169 "Derived-to-base conversion",
170 "Vector conversion",
171 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000172 "Complex-real conversion",
173 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000174 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000175 "Writeback conversion",
176 "OpenCL Zero Event Conversion",
George Burgess IV2099b542016-09-02 22:59:57 +0000177 "C specific type conversion",
178 "Incompatible pointer conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000179 };
180 return Name[Kind];
181}
182
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000183/// StandardConversionSequence - Set the standard conversion
184/// sequence to the identity conversion.
185void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000189 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000190 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000191 ReferenceBinding = false;
192 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000197 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000198 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000199}
200
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000201/// getRank - Retrieve the rank of this standard conversion sequence
202/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203/// implicit conversions.
204ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
212 return Rank;
213}
214
215/// isPointerConversionToBool - Determines whether this conversion is
216/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000217/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000219bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
223 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000224 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000225 (getFromType()->isPointerType() ||
226 getFromType()->isObjCObjectPointerType() ||
227 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000228 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230 return true;
231
232 return false;
233}
234
Douglas Gregor5c407d92008-10-23 00:40:37 +0000235/// isPointerConversionToVoidPointer - Determines whether this
236/// conversion is a conversion of a pointer to a void pointer. This is
237/// used as part of the ranking of standard conversion sequences (C++
238/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000239bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000241isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000242 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000243 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000244
245 // Note that FromType has not necessarily been transformed by the
246 // array-to-pointer implicit conversion, so check for its presence
247 // and redo the conversion to get a pointer.
248 if (First == ICK_Array_To_Pointer)
249 FromType = Context.getArrayDecayedType(FromType);
250
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000253 return ToPtrType->getPointeeType()->isVoidType();
254
255 return false;
256}
257
Richard Smith66e05fe2012-01-18 05:21:49 +0000258/// Skip any implicit casts which could be either part of a narrowing conversion
259/// or after one in an implicit conversion.
260static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
261 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
262 switch (ICE->getCastKind()) {
263 case CK_NoOp:
264 case CK_IntegralCast:
265 case CK_IntegralToBoolean:
266 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000267 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000268 case CK_FloatingToIntegral:
269 case CK_FloatingToBoolean:
270 case CK_FloatingCast:
271 Converted = ICE->getSubExpr();
272 continue;
273
274 default:
275 return Converted;
276 }
277 }
278
279 return Converted;
280}
281
282/// Check if this standard conversion sequence represents a narrowing
283/// conversion, according to C++11 [dcl.init.list]p7.
284///
285/// \param Ctx The AST context.
286/// \param Converted The result of applying this standard conversion sequence.
287/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
288/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000289/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
290/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000291NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000292StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
293 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000294 APValue &ConstantValue,
295 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000296 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000297
298 // C++11 [dcl.init.list]p7:
299 // A narrowing conversion is an implicit conversion ...
300 QualType FromType = getToType(0);
301 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000302
303 // A conversion to an enumeration type is narrowing if the conversion to
304 // the underlying type is narrowing. This only arises for expressions of
305 // the form 'Enum{init}'.
306 if (auto *ET = ToType->getAs<EnumType>())
307 ToType = ET->getDecl()->getIntegerType();
308
Richard Smith66e05fe2012-01-18 05:21:49 +0000309 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000310 // 'bool' is an integral type; dispatch to the right place to handle it.
311 case ICK_Boolean_Conversion:
312 if (FromType->isRealFloatingType())
313 goto FloatingIntegralConversion;
314 if (FromType->isIntegralOrUnscopedEnumerationType())
315 goto IntegralConversion;
316 // Boolean conversions can be from pointers and pointers to members
317 // [conv.bool], and those aren't considered narrowing conversions.
318 return NK_Not_Narrowing;
319
Richard Smith66e05fe2012-01-18 05:21:49 +0000320 // -- from a floating-point type to an integer type, or
321 //
322 // -- from an integer type or unscoped enumeration type to a floating-point
323 // type, except where the source is a constant expression and the actual
324 // value after conversion will fit into the target type and will produce
325 // the original value when converted back to the original type, or
326 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000327 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329 return NK_Type_Narrowing;
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 SlabAllocator.Reset();
843 NumInlineBytesUsed = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000844 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000845 Functions.clear();
846}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000847
John McCall4124c492011-10-17 18:40:02 +0000848namespace {
849 class UnbridgedCastsSet {
850 struct Entry {
851 Expr **Addr;
852 Expr *Saved;
853 };
854 SmallVector<Entry, 2> Entries;
855
856 public:
857 void save(Sema &S, Expr *&E) {
858 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
859 Entry entry = { &E, E };
860 Entries.push_back(entry);
861 E = S.stripARCUnbridgedCast(E);
862 }
863
864 void restore() {
865 for (SmallVectorImpl<Entry>::iterator
866 i = Entries.begin(), e = Entries.end(); i != e; ++i)
867 *i->Addr = i->Saved;
868 }
869 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000870}
John McCall4124c492011-10-17 18:40:02 +0000871
872/// checkPlaceholderForOverload - Do any interesting placeholder-like
873/// preprocessing on the given expression.
874///
875/// \param unbridgedCasts a collection to which to add unbridged casts;
876/// without this, they will be immediately diagnosed as errors
877///
878/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000879static bool
880checkPlaceholderForOverload(Sema &S, Expr *&E,
881 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000882 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
883 // We can't handle overloaded expressions here because overload
884 // resolution might reasonably tweak them.
885 if (placeholder->getKind() == BuiltinType::Overload) return false;
886
887 // If the context potentially accepts unbridged ARC casts, strip
888 // the unbridged cast and add it to the collection for later restoration.
889 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
890 unbridgedCasts) {
891 unbridgedCasts->save(S, E);
892 return false;
893 }
894
895 // Go ahead and check everything else.
896 ExprResult result = S.CheckPlaceholderExpr(E);
897 if (result.isInvalid())
898 return true;
899
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000900 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000901 return false;
902 }
903
904 // Nothing to do.
905 return false;
906}
907
908/// checkArgPlaceholdersForOverload - Check a set of call operands for
909/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000910static bool checkArgPlaceholdersForOverload(Sema &S,
911 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000912 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000913 for (unsigned i = 0, e = Args.size(); i != e; ++i)
914 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000915 return true;
916
917 return false;
918}
919
George Burgess IV2d82b092017-04-06 00:23:31 +0000920/// Determine whether the given New declaration is an overload of the
921/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
922/// New and Old cannot be overloaded, e.g., if New has the same signature as
923/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
924/// functions (or function templates) at all. When it does return Ovl_Match or
925/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
926/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
927/// declaration.
928///
929/// Example: Given the following input:
930///
931/// void f(int, float); // #1
932/// void f(int, int); // #2
933/// int f(int, int); // #3
934///
935/// When we process #1, there is no previous declaration of "f", so IsOverload
936/// will not be used.
937///
938/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
939/// the parameter types, we see that #1 and #2 are overloaded (since they have
940/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
941/// unchanged.
942///
943/// When we process #3, Old is an overload set containing #1 and #2. We compare
944/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
945/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
946/// functions are not part of the signature), IsOverload returns Ovl_Match and
947/// MatchedDecl will be set to point to the FunctionDecl for #2.
948///
949/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
950/// by a using declaration. The rules for whether to hide shadow declarations
951/// ignore some properties which otherwise figure into a function template's
952/// signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000953Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000954Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
955 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000956 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000957 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000958 NamedDecl *OldD = *I;
959
960 bool OldIsUsingDecl = false;
961 if (isa<UsingShadowDecl>(OldD)) {
962 OldIsUsingDecl = true;
963
964 // We can always introduce two using declarations into the same
965 // context, even if they have identical signatures.
966 if (NewIsUsingDecl) continue;
967
968 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
969 }
970
Richard Smithf091e122015-09-15 01:28:55 +0000971 // A using-declaration does not conflict with another declaration
972 // if one of them is hidden.
973 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
974 continue;
975
John McCalle9cccd82010-06-16 08:42:20 +0000976 // If either declaration was introduced by a using declaration,
977 // we'll need to use slightly different rules for matching.
978 // Essentially, these rules are the normal rules, except that
979 // function templates hide function templates with different
980 // return types or template parameter lists.
981 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000982 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
983 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000984
Alp Tokera2794f92014-01-22 07:29:52 +0000985 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000986 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
987 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
988 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
989 continue;
990 }
991
Alp Tokera2794f92014-01-22 07:29:52 +0000992 if (!isa<FunctionTemplateDecl>(OldD) &&
993 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000994 continue;
995
John McCalldaa3d6b2009-12-09 03:35:25 +0000996 Match = *I;
997 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000998 }
Richard Smith151c4562016-12-20 21:35:28 +0000999 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001000 // We can overload with these, which can show up when doing
1001 // redeclaration checks for UsingDecls.
1002 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +00001003 } else if (isa<TagDecl>(OldD)) {
1004 // We can always overload with tags by hiding them.
Richard Smithd8a9e372016-12-18 21:39:37 +00001005 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +00001006 // Optimistically assume that an unresolved using decl will
1007 // overload; if it doesn't, we'll have to diagnose during
1008 // template instantiation.
Richard Smithd8a9e372016-12-18 21:39:37 +00001009 //
1010 // Exception: if the scope is dependent and this is not a class
1011 // member, the using declaration can only introduce an enumerator.
1012 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1013 Match = *I;
1014 return Ovl_NonFunction;
1015 }
John McCall84d87672009-12-10 09:41:52 +00001016 } else {
John McCall1f82f242009-11-18 22:49:29 +00001017 // (C++ 13p1):
1018 // Only function declarations can be overloaded; object and type
1019 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +00001020 Match = *I;
1021 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +00001022 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001023 }
John McCall1f82f242009-11-18 22:49:29 +00001024
John McCalldaa3d6b2009-12-09 03:35:25 +00001025 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +00001026}
1027
Richard Smithac974a32013-06-30 09:48:50 +00001028bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +00001029 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +00001030 // C++ [basic.start.main]p2: This function shall not be overloaded.
1031 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001032 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001033
David Majnemerc729b0b2013-09-16 22:44:20 +00001034 // MSVCRT user defined entry points cannot be overloaded.
1035 if (New->isMSVCRTEntryPoint())
1036 return false;
1037
John McCall1f82f242009-11-18 22:49:29 +00001038 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1039 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1040
1041 // C++ [temp.fct]p2:
1042 // A function template can be overloaded with other function templates
1043 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001044 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001045 return true;
1046
1047 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001048 QualType OldQType = Context.getCanonicalType(Old->getType());
1049 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001050
1051 // Compare the signatures (C++ 1.3.10) of the two functions to
1052 // determine whether they are overloads. If we find any mismatch
1053 // in the signature, they are overloads.
1054
1055 // If either of these functions is a K&R-style function (no
1056 // prototype), then we consider them to have matching signatures.
1057 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1058 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1059 return false;
1060
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001061 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1062 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001063
1064 // The signature of a function includes the types of its
1065 // parameters (C++ 1.3.10), which includes the presence or absence
1066 // of the ellipsis; see C++ DR 357).
1067 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001068 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001069 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001070 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001071 return true;
1072
1073 // C++ [temp.over.link]p4:
1074 // The signature of a function template consists of its function
1075 // signature, its return type and its template parameter list. The names
1076 // of the template parameters are significant only for establishing the
1077 // relationship between the template parameters and the rest of the
1078 // signature.
1079 //
1080 // We check the return type and template parameter lists for function
1081 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001082 //
1083 // However, we don't consider either of these when deciding whether
1084 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001085 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001086 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1087 OldTemplate->getTemplateParameters(),
1088 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001089 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001090 return true;
1091
1092 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001093 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001094 //
1095 // As part of this, also check whether one of the member functions
1096 // is static, in which case they are not overloads (C++
1097 // 13.1p2). While not part of the definition of the signature,
1098 // this check is important to determine whether these functions
1099 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001100 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1101 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001102 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001103 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1104 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001105 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001106 (OldMethod->getRefQualifier() == RQ_None ||
1107 NewMethod->getRefQualifier() == RQ_None)) {
1108 // C++0x [over.load]p2:
1109 // - Member function declarations with the same name and the same
1110 // parameter-type-list as well as member function template
1111 // declarations with the same name, the same parameter-type-list, and
1112 // the same template parameter lists cannot be overloaded if any of
1113 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001114 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001115 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001116 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001117 }
1118 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120
Richard Smith574f4f62013-01-14 05:37:29 +00001121 // We may not have applied the implicit const for a constexpr member
1122 // function yet (because we haven't yet resolved whether this is a static
1123 // or non-static member function). Add it now, on the assumption that this
1124 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001125 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001126 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001127 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001128 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001129 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001130
1131 // We do not allow overloading based off of '__restrict'.
1132 OldQuals &= ~Qualifiers::Restrict;
1133 NewQuals &= ~Qualifiers::Restrict;
1134 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001135 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001137
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001138 // Though pass_object_size is placed on parameters and takes an argument, we
1139 // consider it to be a function-level modifier for the sake of function
1140 // identity. Either the function has one or more parameters with
1141 // pass_object_size or it doesn't.
1142 if (functionHasPassObjectSizeParams(New) !=
1143 functionHasPassObjectSizeParams(Old))
1144 return true;
1145
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001146 // enable_if attributes are an order-sensitive part of the signature.
1147 for (specific_attr_iterator<EnableIfAttr>
1148 NewI = New->specific_attr_begin<EnableIfAttr>(),
1149 NewE = New->specific_attr_end<EnableIfAttr>(),
1150 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1151 OldE = Old->specific_attr_end<EnableIfAttr>();
1152 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1153 if (NewI == NewE || OldI == OldE)
1154 return true;
1155 llvm::FoldingSetNodeID NewID, OldID;
1156 NewI->getCond()->Profile(NewID, Context, true);
1157 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001158 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001159 return true;
1160 }
1161
Justin Lebarba122ab2016-03-30 23:30:21 +00001162 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Justin Lebare060feb2016-10-03 16:48:23 +00001163 // Don't allow overloading of destructors. (In theory we could, but it
1164 // would be a giant change to clang.)
1165 if (isa<CXXDestructorDecl>(New))
1166 return false;
1167
Artem Belevich94a55e82015-09-22 17:22:59 +00001168 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1169 OldTarget = IdentifyCUDATarget(Old);
Artem Belevich13e9b4d2016-12-07 19:27:16 +00001170 if (NewTarget == CFT_InvalidTarget)
Artem Belevich94a55e82015-09-22 17:22:59 +00001171 return false;
1172
1173 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1174
Justin Lebar53b000af2016-10-03 16:48:27 +00001175 // Allow overloading of functions with same signature and different CUDA
1176 // target attributes.
Artem Belevich94a55e82015-09-22 17:22:59 +00001177 return NewTarget != OldTarget;
1178 }
1179
John McCall1f82f242009-11-18 22:49:29 +00001180 // The signatures match; this is not an overload.
1181 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001182}
1183
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001184/// \brief Checks availability of the function depending on the current
1185/// function context. Inside an unavailable function, unavailability is ignored.
1186///
1187/// \returns true if \arg FD is unavailable and current context is inside
1188/// an available function, false otherwise.
1189bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001190 if (!FD->isUnavailable())
1191 return false;
1192
1193 // Walk up the context of the caller.
1194 Decl *C = cast<Decl>(CurContext);
1195 do {
1196 if (C->isUnavailable())
1197 return false;
1198 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1199 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001200}
1201
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001202/// \brief Tries a user-defined conversion from From to ToType.
1203///
1204/// Produces an implicit conversion sequence for when a standard conversion
1205/// is not an option. See TryImplicitConversion for more information.
1206static ImplicitConversionSequence
1207TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1208 bool SuppressUserConversions,
1209 bool AllowExplicit,
1210 bool InOverloadResolution,
1211 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001212 bool AllowObjCWritebackConversion,
1213 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001214 ImplicitConversionSequence ICS;
1215
1216 if (SuppressUserConversions) {
1217 // We're not in the case above, so there is no conversion that
1218 // we can perform.
1219 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1220 return ICS;
1221 }
1222
1223 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001224 OverloadCandidateSet Conversions(From->getExprLoc(),
1225 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001226 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1227 Conversions, AllowExplicit,
1228 AllowObjCConversionOnExplicit)) {
1229 case OR_Success:
1230 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001231 ICS.setUserDefined();
1232 // C++ [over.ics.user]p4:
1233 // A conversion of an expression of class type to the same class
1234 // type is given Exact Match rank, and a conversion of an
1235 // expression of class type to a base class of that type is
1236 // given Conversion rank, in spite of the fact that a copy
1237 // constructor (i.e., a user-defined conversion function) is
1238 // called for those cases.
1239 if (CXXConstructorDecl *Constructor
1240 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1241 QualType FromCanon
1242 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1243 QualType ToCanon
1244 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1245 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001246 (FromCanon == ToCanon ||
1247 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001248 // Turn this into a "standard" conversion sequence, so that it
1249 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001250 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001251 ICS.setStandard();
1252 ICS.Standard.setAsIdentityConversion();
1253 ICS.Standard.setFromType(From->getType());
1254 ICS.Standard.setAllToTypes(ToType);
1255 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001256 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001257 if (ToCanon != FromCanon)
1258 ICS.Standard.Second = ICK_Derived_To_Base;
1259 }
1260 }
Richard Smith48372b62015-01-27 03:30:40 +00001261 break;
1262
1263 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001264 ICS.setAmbiguous();
1265 ICS.Ambiguous.setFromType(From->getType());
1266 ICS.Ambiguous.setToType(ToType);
1267 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1268 Cand != Conversions.end(); ++Cand)
1269 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001270 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001271 break;
Richard Smith48372b62015-01-27 03:30:40 +00001272
1273 // Fall through.
1274 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001275 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001276 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001277 }
1278
1279 return ICS;
1280}
1281
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001282/// TryImplicitConversion - Attempt to perform an implicit conversion
1283/// from the given expression (Expr) to the given type (ToType). This
1284/// function returns an implicit conversion sequence that can be used
1285/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001286///
1287/// void f(float f);
1288/// void g(int i) { f(i); }
1289///
1290/// this routine would produce an implicit conversion sequence to
1291/// describe the initialization of f from i, which will be a standard
1292/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1293/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1294//
1295/// Note that this routine only determines how the conversion can be
1296/// performed; it does not actually perform the conversion. As such,
1297/// it will not produce any diagnostics if no conversion is available,
1298/// but will instead return an implicit conversion sequence of kind
1299/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001300///
1301/// If @p SuppressUserConversions, then user-defined conversions are
1302/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001303/// If @p AllowExplicit, then explicit user-defined conversions are
1304/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001305///
1306/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1307/// writeback conversion, which allows __autoreleasing id* parameters to
1308/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001309static ImplicitConversionSequence
1310TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1311 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001312 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001313 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001314 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001315 bool AllowObjCWritebackConversion,
1316 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001317 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001318 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001319 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001320 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001321 return ICS;
1322 }
1323
David Blaikiebbafb8a2012-03-11 07:00:24 +00001324 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001325 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001326 return ICS;
1327 }
1328
Douglas Gregor836a7e82010-08-11 02:15:33 +00001329 // C++ [over.ics.user]p4:
1330 // A conversion of an expression of class type to the same class
1331 // type is given Exact Match rank, and a conversion of an
1332 // expression of class type to a base class of that type is
1333 // given Conversion rank, in spite of the fact that a copy/move
1334 // constructor (i.e., a user-defined conversion function) is
1335 // called for those cases.
1336 QualType FromType = From->getType();
1337 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001338 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001339 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001340 ICS.setStandard();
1341 ICS.Standard.setAsIdentityConversion();
1342 ICS.Standard.setFromType(FromType);
1343 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344
Douglas Gregor5ab11652010-04-17 22:01:05 +00001345 // We don't actually check at this point whether there is a valid
1346 // copy/move constructor, since overloading just assumes that it
1347 // exists. When we actually perform initialization, we'll find the
1348 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001349 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001350
Douglas Gregor5ab11652010-04-17 22:01:05 +00001351 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001352 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001353 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001354
Douglas Gregor836a7e82010-08-11 02:15:33 +00001355 return ICS;
1356 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001358 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1359 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001360 AllowObjCWritebackConversion,
1361 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001362}
1363
John McCall31168b02011-06-15 23:02:42 +00001364ImplicitConversionSequence
1365Sema::TryImplicitConversion(Expr *From, QualType ToType,
1366 bool SuppressUserConversions,
1367 bool AllowExplicit,
1368 bool InOverloadResolution,
1369 bool CStyle,
1370 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001371 return ::TryImplicitConversion(*this, From, ToType,
1372 SuppressUserConversions, AllowExplicit,
1373 InOverloadResolution, CStyle,
1374 AllowObjCWritebackConversion,
1375 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001376}
1377
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001378/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001379/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001380/// converted expression. Flavor is the kind of conversion we're
1381/// performing, used in the error message. If @p AllowExplicit,
1382/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001383ExprResult
1384Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001385 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001386 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001387 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001388}
1389
John Wiegley01296292011-04-08 18:41:53 +00001390ExprResult
1391Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001392 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001393 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001394 if (checkPlaceholderForOverload(*this, From))
1395 return ExprError();
1396
John McCall31168b02011-06-15 23:02:42 +00001397 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1398 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001399 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001400 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001401 if (getLangOpts().ObjC1)
1402 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1403 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001404 ICS = ::TryImplicitConversion(*this, From, ToType,
1405 /*SuppressUserConversions=*/false,
1406 AllowExplicit,
1407 /*InOverloadResolution=*/false,
1408 /*CStyle=*/false,
1409 AllowObjCWritebackConversion,
1410 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001411 return PerformImplicitConversion(From, ToType, ICS, Action);
1412}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001413
1414/// \brief Determine whether the conversion from FromType to ToType is a valid
Richard Smith3c4f8d22016-10-16 17:54:23 +00001415/// conversion that strips "noexcept" or "noreturn" off the nested function
1416/// type.
1417bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
Chandler Carruth53e61b02011-06-18 01:19:03 +00001418 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001419 if (Context.hasSameUnqualifiedType(FromType, ToType))
1420 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001421
John McCall991eb4b2010-12-21 00:44:39 +00001422 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
Richard Smith3c4f8d22016-10-16 17:54:23 +00001423 // or F(t noexcept) -> F(t)
John McCall991eb4b2010-12-21 00:44:39 +00001424 // where F adds one of the following at most once:
1425 // - a pointer
1426 // - a member pointer
1427 // - a block pointer
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001428 // Changes here need matching changes in FindCompositePointerType.
John McCall991eb4b2010-12-21 00:44:39 +00001429 CanQualType CanTo = Context.getCanonicalType(ToType);
1430 CanQualType CanFrom = Context.getCanonicalType(FromType);
1431 Type::TypeClass TyClass = CanTo->getTypeClass();
1432 if (TyClass != CanFrom->getTypeClass()) return false;
1433 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1434 if (TyClass == Type::Pointer) {
1435 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1436 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1437 } else if (TyClass == Type::BlockPointer) {
1438 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1439 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1440 } else if (TyClass == Type::MemberPointer) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001441 auto ToMPT = CanTo.getAs<MemberPointerType>();
1442 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1443 // A function pointer conversion cannot change the class of the function.
1444 if (ToMPT->getClass() != FromMPT->getClass())
1445 return false;
1446 CanTo = ToMPT->getPointeeType();
1447 CanFrom = FromMPT->getPointeeType();
John McCall991eb4b2010-12-21 00:44:39 +00001448 } else {
1449 return false;
1450 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001451
John McCall991eb4b2010-12-21 00:44:39 +00001452 TyClass = CanTo->getTypeClass();
1453 if (TyClass != CanFrom->getTypeClass()) return false;
1454 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1455 return false;
1456 }
1457
Richard Smith3c4f8d22016-10-16 17:54:23 +00001458 const auto *FromFn = cast<FunctionType>(CanFrom);
1459 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
John McCall991eb4b2010-12-21 00:44:39 +00001460
Richard Smith6f427402016-10-20 00:01:36 +00001461 const auto *ToFn = cast<FunctionType>(CanTo);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001462 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1463
1464 bool Changed = false;
1465
1466 // Drop 'noreturn' if not present in target type.
1467 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1468 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1469 Changed = true;
1470 }
1471
1472 // Drop 'noexcept' if not present in target type.
1473 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
Richard Smith6f427402016-10-20 00:01:36 +00001474 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
Richard Smith3c4f8d22016-10-16 17:54:23 +00001475 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1476 FromFn = cast<FunctionType>(
1477 Context.getFunctionType(FromFPT->getReturnType(),
1478 FromFPT->getParamTypes(),
1479 FromFPT->getExtProtoInfo().withExceptionSpec(
1480 FunctionProtoType::ExceptionSpecInfo()))
1481 .getTypePtr());
1482 Changed = true;
1483 }
1484 }
1485
1486 if (!Changed)
1487 return false;
1488
John McCall991eb4b2010-12-21 00:44:39 +00001489 assert(QualType(FromFn, 0).isCanonical());
1490 if (QualType(FromFn, 0) != CanTo) return false;
1491
1492 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001493 return true;
1494}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495
Douglas Gregor46188682010-05-18 22:42:18 +00001496/// \brief Determine whether the conversion from FromType to ToType is a valid
1497/// vector conversion.
1498///
1499/// \param ICK Will be set to the vector conversion kind, if this is a vector
1500/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001501static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001502 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001503 // We need at least one of these types to be a vector type to have a vector
1504 // conversion.
1505 if (!ToType->isVectorType() && !FromType->isVectorType())
1506 return false;
1507
1508 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001509 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001510 return false;
1511
1512 // There are no conversions between extended vector types, only identity.
1513 if (ToType->isExtVectorType()) {
1514 // There are no conversions between extended vector types other than the
1515 // identity conversion.
1516 if (FromType->isExtVectorType())
1517 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001518
Douglas Gregor46188682010-05-18 22:42:18 +00001519 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001520 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001521 ICK = ICK_Vector_Splat;
1522 return true;
1523 }
1524 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001525
1526 // We can perform the conversion between vector types in the following cases:
1527 // 1)vector types are equivalent AltiVec and GCC vector types
1528 // 2)lax vector conversions are permitted and the vector types are of the
1529 // same size
1530 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001531 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1532 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001533 ICK = ICK_Vector_Conversion;
1534 return true;
1535 }
Douglas Gregor46188682010-05-18 22:42:18 +00001536 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001537
Douglas Gregor46188682010-05-18 22:42:18 +00001538 return false;
1539}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001540
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001541static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1542 bool InOverloadResolution,
1543 StandardConversionSequence &SCS,
1544 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001545
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001546/// IsStandardConversion - Determines whether there is a standard
1547/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1548/// expression From to the type ToType. Standard conversion sequences
1549/// only consider non-class types; for conversions that involve class
1550/// types, use TryImplicitConversion. If a conversion exists, SCS will
1551/// contain the standard conversion sequence required to perform this
1552/// conversion and this routine will return true. Otherwise, this
1553/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001554static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1555 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001556 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001557 bool CStyle,
1558 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001559 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001560
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001561 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001562 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001563 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001564 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001565 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001566
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001567 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001568 // abort early. When overloading in C, however, we do permit them.
1569 if (S.getLangOpts().CPlusPlus &&
1570 (FromType->isRecordType() || ToType->isRecordType()))
1571 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001572
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001573 // The first conversion can be an lvalue-to-rvalue conversion,
1574 // array-to-pointer conversion, or function-to-pointer conversion
1575 // (C++ 4p1).
1576
John McCall5c32be02010-08-24 20:38:10 +00001577 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001578 DeclAccessPair AccessPair;
1579 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001580 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001581 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001582 // We were able to resolve the address of the overloaded function,
1583 // so we can convert to the type of that function.
1584 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001585 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001586
1587 // we can sometimes resolve &foo<int> regardless of ToType, so check
1588 // if the type matches (identity) or we are converting to bool
1589 if (!S.Context.hasSameUnqualifiedType(
1590 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1591 QualType resultTy;
1592 // if the function type matches except for [[noreturn]], it's ok
Richard Smith3c4f8d22016-10-16 17:54:23 +00001593 if (!S.IsFunctionConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001594 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1595 // otherwise, only a boolean conversion is standard
1596 if (!ToType->isBooleanType())
1597 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001598 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001599
Chandler Carruthffce2452011-03-29 08:08:18 +00001600 // Check if the "from" expression is taking the address of an overloaded
1601 // function and recompute the FromType accordingly. Take advantage of the
1602 // fact that non-static member functions *must* have such an address-of
1603 // expression.
1604 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1605 if (Method && !Method->isStatic()) {
1606 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1607 "Non-unary operator on non-static member address");
1608 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1609 == UO_AddrOf &&
1610 "Non-address-of operator on non-static member address");
1611 const Type *ClassType
1612 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1613 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001614 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1615 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1616 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001617 "Non-address-of operator for overloaded function expression");
1618 FromType = S.Context.getPointerType(FromType);
1619 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001620
Douglas Gregor980fb162010-04-29 18:24:40 +00001621 // Check that we've computed the proper type after overload resolution.
Richard Smith9095e5b2016-11-01 01:31:23 +00001622 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1623 // be calling it from within an NDEBUG block.
Chandler Carruthffce2452011-03-29 08:08:18 +00001624 assert(S.Context.hasSameType(
1625 FromType,
1626 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001627 } else {
1628 return false;
1629 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001630 }
John McCall154a2fd2011-08-30 00:57:29 +00001631 // Lvalue-to-rvalue conversion (C++11 4.1):
1632 // A glvalue (3.10) of a non-function, non-array type T can
1633 // be converted to a prvalue.
1634 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001635 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001636 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001637 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001638 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001639
Douglas Gregorc79862f2012-04-12 17:51:55 +00001640 // C11 6.3.2.1p2:
1641 // ... if the lvalue has atomic type, the value has the non-atomic version
1642 // of the type of the lvalue ...
1643 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1644 FromType = Atomic->getValueType();
1645
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001646 // If T is a non-class type, the type of the rvalue is the
1647 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001648 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1649 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001650 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001651 } else if (FromType->isArrayType()) {
1652 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001653 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001654
1655 // An lvalue or rvalue of type "array of N T" or "array of unknown
1656 // bound of T" can be converted to an rvalue of type "pointer to
1657 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001658 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001659
John McCall5c32be02010-08-24 20:38:10 +00001660 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001661 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001662 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663
1664 // For the purpose of ranking in overload resolution
1665 // (13.3.3.1.1), this conversion is considered an
1666 // array-to-pointer conversion followed by a qualification
1667 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001668 SCS.Second = ICK_Identity;
1669 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001670 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001671 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001672 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001673 }
John McCall086a4642010-11-24 05:12:34 +00001674 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001675 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001676 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001677
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001678 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1679 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1680 if (!S.checkAddressOfFunctionIsAvailable(FD))
1681 return false;
1682
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001683 // An lvalue of function type T can be converted to an rvalue of
1684 // type "pointer to T." The result is a pointer to the
1685 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001686 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001687 } else {
1688 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001689 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001690 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001691 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001692
1693 // The second conversion can be an integral promotion, floating
1694 // point promotion, integral conversion, floating point conversion,
1695 // floating-integral conversion, pointer conversion,
1696 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001697 // For overloading in C, this can also be a "compatible-type"
1698 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001699 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001700 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001701 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001702 // The unqualified versions of the types are the same: there's no
1703 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001704 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001705 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001706 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001707 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001708 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001709 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001710 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001711 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001712 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001713 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001714 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001715 SCS.Second = ICK_Complex_Promotion;
1716 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001717 } else if (ToType->isBooleanType() &&
1718 (FromType->isArithmeticType() ||
1719 FromType->isAnyPointerType() ||
1720 FromType->isBlockPointerType() ||
1721 FromType->isMemberPointerType() ||
1722 FromType->isNullPtrType())) {
1723 // Boolean conversions (C++ 4.12).
1724 SCS.Second = ICK_Boolean_Conversion;
1725 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001726 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001727 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001728 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001729 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001730 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001731 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001732 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001733 SCS.Second = ICK_Complex_Conversion;
1734 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001735 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1736 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001737 // Complex-real conversions (C99 6.3.1.7)
1738 SCS.Second = ICK_Complex_Real;
1739 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001740 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001741 // FIXME: disable conversions between long double and __float128 if
1742 // their representation is different until there is back end support
1743 // We of course allow this conversion if long double is really double.
1744 if (&S.Context.getFloatTypeSemantics(FromType) !=
1745 &S.Context.getFloatTypeSemantics(ToType)) {
1746 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1747 ToType == S.Context.LongDoubleTy) ||
1748 (FromType == S.Context.LongDoubleTy &&
1749 ToType == S.Context.Float128Ty));
1750 if (Float128AndLongDouble &&
1751 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001752 &llvm::APFloat::IEEEdouble()))
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001753 return false;
1754 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001755 // Floating point conversions (C++ 4.8).
1756 SCS.Second = ICK_Floating_Conversion;
1757 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001758 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001759 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001760 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001761 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001762 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001763 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001764 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001765 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001766 SCS.Second = ICK_Block_Pointer_Conversion;
1767 } else if (AllowObjCWritebackConversion &&
1768 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1769 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001770 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1771 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001772 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001773 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001774 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001775 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001776 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001777 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001778 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001779 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001780 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001781 SCS.Second = SecondICK;
1782 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001783 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001784 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001785 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001786 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001787 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001788 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1789 InOverloadResolution,
1790 SCS, CStyle)) {
1791 SCS.Second = ICK_TransparentUnionConversion;
1792 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001793 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1794 CStyle)) {
1795 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001796 // appropriately.
1797 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001798 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001799 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001800 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001801 SCS.Second = ICK_Zero_Event_Conversion;
1802 FromType = ToType;
Egor Churaev89831422016-12-23 14:55:49 +00001803 } else if (ToType->isQueueT() &&
1804 From->isIntegerConstantExpr(S.getASTContext()) &&
1805 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1806 SCS.Second = ICK_Zero_Queue_Conversion;
1807 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001808 } else {
1809 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001810 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001811 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001812 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001813
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001814 // The third conversion can be a function pointer conversion or a
1815 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
John McCall31168b02011-06-15 23:02:42 +00001816 bool ObjCLifetimeConversion;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001817 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1818 // Function pointer conversions (removing 'noexcept') including removal of
1819 // 'noreturn' (Clang extension).
1820 SCS.Third = ICK_Function_Conversion;
1821 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1822 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001823 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001824 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001825 FromType = ToType;
1826 } else {
1827 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001828 SCS.Third = ICK_Identity;
Richard Smith9c37e662016-10-20 17:57:33 +00001829 }
Richard Smitheb7ef2e2016-10-20 21:53:09 +00001830
1831 // C++ [over.best.ics]p6:
1832 // [...] Any difference in top-level cv-qualification is
1833 // subsumed by the initialization itself and does not constitute
1834 // a conversion. [...]
1835 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1836 QualType CanonTo = S.Context.getCanonicalType(ToType);
1837 if (CanonFrom.getLocalUnqualifiedType()
1838 == CanonTo.getLocalUnqualifiedType() &&
1839 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1840 FromType = ToType;
1841 CanonFrom = CanonTo;
1842 }
1843
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001844 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001845
George Burgess IV45461812015-10-11 20:13:20 +00001846 if (CanonFrom == CanonTo)
1847 return true;
1848
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001849 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001850 // this is a bad conversion sequence, unless we're resolving an overload in C.
1851 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001852 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001853
George Burgess IV45461812015-10-11 20:13:20 +00001854 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001855 Sema::AssignConvertType Conv =
1856 S.CheckSingleAssignmentConstraints(ToType, ER,
1857 /*Diagnose=*/false,
1858 /*DiagnoseCFAudited=*/false,
1859 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001860 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001861 switch (Conv) {
1862 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001863 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001864 break;
1865 // For our purposes, discarding qualifiers is just as bad as using an
1866 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1867 // qualifiers, as well.
1868 case Sema::CompatiblePointerDiscardsQualifiers:
1869 case Sema::IncompatiblePointer:
1870 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001871 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001872 break;
1873 default:
George Burgess IV45461812015-10-11 20:13:20 +00001874 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001875 }
George Burgess IV45461812015-10-11 20:13:20 +00001876
George Burgess IV6098fd12016-09-03 00:28:25 +00001877 // First can only be an lvalue conversion, so we pretend that this was the
1878 // second conversion. First should already be valid from earlier in the
1879 // function.
1880 SCS.Second = SecondConv;
1881 SCS.setToType(1, ToType);
1882
1883 // Third is Identity, because Second should rank us worse than any other
1884 // conversion. This could also be ICK_Qualification, but it's simpler to just
1885 // lump everything in with the second conversion, and we don't gain anything
1886 // from making this ICK_Qualification.
1887 SCS.Third = ICK_Identity;
1888 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001889 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001890}
George Burgess IV2099b542016-09-02 22:59:57 +00001891
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001892static bool
1893IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1894 QualType &ToType,
1895 bool InOverloadResolution,
1896 StandardConversionSequence &SCS,
1897 bool CStyle) {
1898
1899 const RecordType *UT = ToType->getAsUnionType();
1900 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1901 return false;
1902 // The field to initialize within the transparent union.
1903 RecordDecl *UD = UT->getDecl();
1904 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001905 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001906 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1907 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001908 ToType = it->getType();
1909 return true;
1910 }
1911 }
1912 return false;
1913}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001914
1915/// IsIntegralPromotion - Determines whether the conversion from the
1916/// expression From (whose potentially-adjusted type is FromType) to
1917/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1918/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001919bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001920 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001921 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001922 if (!To) {
1923 return false;
1924 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001925
1926 // An rvalue of type char, signed char, unsigned char, short int, or
1927 // unsigned short int can be converted to an rvalue of type int if
1928 // int can represent all the values of the source type; otherwise,
1929 // the source rvalue can be converted to an rvalue of type unsigned
1930 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001931 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1932 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001933 if (// We can promote any signed, promotable integer type to an int
1934 (FromType->isSignedIntegerType() ||
1935 // We can promote any unsigned integer type whose size is
1936 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001937 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001938 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001939 }
1940
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001941 return To->getKind() == BuiltinType::UInt;
1942 }
1943
Richard Smithb9c5a602012-09-13 21:18:54 +00001944 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945 // A prvalue of an unscoped enumeration type whose underlying type is not
1946 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1947 // following types that can represent all the values of the enumeration
1948 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1949 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001950 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001951 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001952 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001953 // with lowest integer conversion rank (4.13) greater than the rank of long
1954 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001955 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001956 // C++11 [conv.prom]p4:
1957 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1958 // can be converted to a prvalue of its underlying type. Moreover, if
1959 // integral promotion can be applied to its underlying type, a prvalue of an
1960 // unscoped enumeration type whose underlying type is fixed can also be
1961 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001962 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1963 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1964 // provided for a scoped enumeration.
1965 if (FromEnumType->getDecl()->isScoped())
1966 return false;
1967
Richard Smithb9c5a602012-09-13 21:18:54 +00001968 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001969 // even if that's not the promoted type. Note that the check for promoting
1970 // the underlying type is based on the type alone, and does not consider
1971 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001972 if (FromEnumType->getDecl()->isFixed()) {
1973 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1974 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001975 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001976 }
1977
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001978 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001979 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001980 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001981 return Context.hasSameUnqualifiedType(
1982 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001983 }
John McCall56774992009-12-09 09:09:27 +00001984
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001985 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1987 // to an rvalue a prvalue of the first of the following types that can
1988 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001989 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001991 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001993 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001994 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001995 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001996 // Determine whether the type we're converting from is signed or
1997 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001998 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001999 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002001 // The types we'll try to promote to, in the appropriate
2002 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00002003 QualType PromoteTypes[6] = {
2004 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00002005 Context.LongTy, Context.UnsignedLongTy ,
2006 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002007 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00002008 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002009 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2010 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00002011 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002012 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2013 // We found the type that we can promote to. If this is the
2014 // type we wanted, we have a promotion. Otherwise, no
2015 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002016 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002017 }
2018 }
2019 }
2020
2021 // An rvalue for an integral bit-field (9.6) can be converted to an
2022 // rvalue of type int if int can represent all the values of the
2023 // bit-field; otherwise, it can be converted to unsigned int if
2024 // unsigned int can represent all the values of the bit-field. If
2025 // the bit-field is larger yet, no integral promotion applies to
2026 // it. If the bit-field has an enumerated type, it is treated as any
2027 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00002028 // FIXME: We should delay checking of bit-fields until we actually perform the
2029 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00002030 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00002031 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002032 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00002033 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00002034 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00002035 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00002036 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002037
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002038 // Are we promoting to an int from a bitfield that fits in an int?
2039 if (BitWidth < ToSize ||
2040 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2041 return To->getKind() == BuiltinType::Int;
2042 }
Mike Stump11289f42009-09-09 15:08:12 +00002043
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002044 // Are we promoting to an unsigned int from an unsigned bitfield
2045 // that fits into an unsigned int?
2046 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2047 return To->getKind() == BuiltinType::UInt;
2048 }
Mike Stump11289f42009-09-09 15:08:12 +00002049
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002050 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002051 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002052 }
Richard Smith88f4bba2015-03-26 00:16:07 +00002053 }
Mike Stump11289f42009-09-09 15:08:12 +00002054
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002055 // An rvalue of type bool can be converted to an rvalue of type int,
2056 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002057 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002058 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002059 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002060
2061 return false;
2062}
2063
2064/// IsFloatingPointPromotion - Determines whether the conversion from
2065/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2066/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002067bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002068 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2069 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002070 /// An rvalue of type float can be converted to an rvalue of type
2071 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002072 if (FromBuiltin->getKind() == BuiltinType::Float &&
2073 ToBuiltin->getKind() == BuiltinType::Double)
2074 return true;
2075
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002076 // C99 6.3.1.5p1:
2077 // When a float is promoted to double or long double, or a
2078 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002079 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002080 (FromBuiltin->getKind() == BuiltinType::Float ||
2081 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002082 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2083 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002084 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002085
2086 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002087 if (!getLangOpts().NativeHalfType &&
2088 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002089 ToBuiltin->getKind() == BuiltinType::Float)
2090 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002091 }
2092
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002093 return false;
2094}
2095
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002096/// \brief Determine if a conversion is a complex promotion.
2097///
2098/// A complex promotion is defined as a complex -> complex conversion
2099/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002100/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002101bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002102 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002103 if (!FromComplex)
2104 return false;
2105
John McCall9dd450b2009-09-21 23:43:11 +00002106 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002107 if (!ToComplex)
2108 return false;
2109
2110 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002111 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002112 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002113 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002114}
2115
Douglas Gregor237f96c2008-11-26 23:31:11 +00002116/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2117/// the pointer type FromPtr to a pointer to type ToPointee, with the
2118/// same type qualifiers as FromPtr has on its pointee type. ToType,
2119/// if non-empty, will be a pointer to ToType that may or may not have
2120/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002121///
Mike Stump11289f42009-09-09 15:08:12 +00002122static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002123BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002124 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002125 ASTContext &Context,
2126 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002127 assert((FromPtr->getTypeClass() == Type::Pointer ||
2128 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2129 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130
John McCall31168b02011-06-15 23:02:42 +00002131 /// Conversions to 'id' subsume cv-qualifier conversions.
2132 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002133 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002134
2135 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002136 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002137 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002138 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002139
John McCall31168b02011-06-15 23:02:42 +00002140 if (StripObjCLifetime)
2141 Quals.removeObjCLifetime();
2142
Mike Stump11289f42009-09-09 15:08:12 +00002143 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002144 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002145 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002146 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002147 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002148
2149 // Build a pointer to ToPointee. It has the right qualifiers
2150 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002151 if (isa<ObjCObjectPointerType>(ToType))
2152 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002153 return Context.getPointerType(ToPointee);
2154 }
2155
2156 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002157 QualType QualifiedCanonToPointee
2158 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002159
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002160 if (isa<ObjCObjectPointerType>(ToType))
2161 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2162 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002163}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002164
Mike Stump11289f42009-09-09 15:08:12 +00002165static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002166 bool InOverloadResolution,
2167 ASTContext &Context) {
2168 // Handle value-dependent integral null pointer constants correctly.
2169 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2170 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002171 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002172 return !InOverloadResolution;
2173
Douglas Gregor56751b52009-09-25 04:25:58 +00002174 return Expr->isNullPointerConstant(Context,
2175 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2176 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002177}
Mike Stump11289f42009-09-09 15:08:12 +00002178
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002179/// IsPointerConversion - Determines whether the conversion of the
2180/// expression From, which has the (possibly adjusted) type FromType,
2181/// can be converted to the type ToType via a pointer conversion (C++
2182/// 4.10). If so, returns true and places the converted type (that
2183/// might differ from ToType in its cv-qualifiers at some level) into
2184/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002185///
Douglas Gregora29dc052008-11-27 01:19:21 +00002186/// This routine also supports conversions to and from block pointers
2187/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2188/// pointers to interfaces. FIXME: Once we've determined the
2189/// appropriate overloading rules for Objective-C, we may want to
2190/// split the Objective-C checks into a different routine; however,
2191/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002192/// conversions, so for now they live here. IncompatibleObjC will be
2193/// set if the conversion is an allowed Objective-C conversion that
2194/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002195bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002196 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002197 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002198 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002199 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002200 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2201 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002202 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002203
Mike Stump11289f42009-09-09 15:08:12 +00002204 // Conversion from a null pointer constant to any Objective-C pointer type.
2205 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002206 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002207 ConvertedType = ToType;
2208 return true;
2209 }
2210
Douglas Gregor231d1c62008-11-27 00:15:41 +00002211 // Blocks: Block pointers can be converted to void*.
2212 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002213 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002214 ConvertedType = ToType;
2215 return true;
2216 }
2217 // Blocks: A null pointer constant can be converted to a block
2218 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002219 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002220 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002221 ConvertedType = ToType;
2222 return true;
2223 }
2224
Sebastian Redl576fd422009-05-10 18:38:11 +00002225 // If the left-hand-side is nullptr_t, the right side can be a null
2226 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002227 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002228 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002229 ConvertedType = ToType;
2230 return true;
2231 }
2232
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002233 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002234 if (!ToTypePtr)
2235 return false;
2236
2237 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002238 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002239 ConvertedType = ToType;
2240 return true;
2241 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002242
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002243 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002244 // , including objective-c pointers.
2245 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002246 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002247 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002248 ConvertedType = BuildSimilarlyQualifiedPointerType(
2249 FromType->getAs<ObjCObjectPointerType>(),
2250 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002251 ToType, Context);
2252 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002253 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002254 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002255 if (!FromTypePtr)
2256 return false;
2257
2258 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002259
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002260 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002261 // pointer conversion, so don't do all of the work below.
2262 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2263 return false;
2264
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002265 // An rvalue of type "pointer to cv T," where T is an object type,
2266 // can be converted to an rvalue of type "pointer to cv void" (C++
2267 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002268 if (FromPointeeType->isIncompleteOrObjectType() &&
2269 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002270 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002271 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002272 ToType, Context,
2273 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002274 return true;
2275 }
2276
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002277 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002278 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002279 ToPointeeType->isVoidType()) {
2280 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2281 ToPointeeType,
2282 ToType, Context);
2283 return true;
2284 }
2285
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002286 // When we're overloading in C, we allow a special kind of pointer
2287 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002288 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002289 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002290 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002291 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002292 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002293 return true;
2294 }
2295
Douglas Gregor5c407d92008-10-23 00:40:37 +00002296 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002297 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002298 // An rvalue of type "pointer to cv D," where D is a class type,
2299 // can be converted to an rvalue of type "pointer to cv B," where
2300 // B is a base class (clause 10) of D. If B is an inaccessible
2301 // (clause 11) or ambiguous (10.2) base class of D, a program that
2302 // necessitates this conversion is ill-formed. The result of the
2303 // conversion is a pointer to the base class sub-object of the
2304 // derived class object. The null pointer value is converted to
2305 // the null pointer value of the destination type.
2306 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002307 // Note that we do not check for ambiguity or inaccessibility
2308 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002309 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002310 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002311 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002312 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002313 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002314 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002315 ToType, Context);
2316 return true;
2317 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002318
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002319 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2320 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2321 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2322 ToPointeeType,
2323 ToType, Context);
2324 return true;
2325 }
2326
Douglas Gregora119f102008-12-19 19:13:09 +00002327 return false;
2328}
Douglas Gregoraec25842011-04-26 23:16:46 +00002329
2330/// \brief Adopt the given qualifiers for the given type.
2331static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2332 Qualifiers TQs = T.getQualifiers();
2333
2334 // Check whether qualifiers already match.
2335 if (TQs == Qs)
2336 return T;
2337
2338 if (Qs.compatiblyIncludes(TQs))
2339 return Context.getQualifiedType(T, Qs);
2340
2341 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2342}
Douglas Gregora119f102008-12-19 19:13:09 +00002343
2344/// isObjCPointerConversion - Determines whether this is an
2345/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2346/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002347bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002348 QualType& ConvertedType,
2349 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002350 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002351 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002352
Douglas Gregoraec25842011-04-26 23:16:46 +00002353 // The set of qualifiers on the type we're converting from.
2354 Qualifiers FromQualifiers = FromType.getQualifiers();
2355
Steve Naroff7cae42b2009-07-10 23:34:53 +00002356 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002357 const ObjCObjectPointerType* ToObjCPtr =
2358 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002359 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002360 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002361
Steve Naroff7cae42b2009-07-10 23:34:53 +00002362 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002363 // If the pointee types are the same (ignoring qualifications),
2364 // then this is not a pointer conversion.
2365 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2366 FromObjCPtr->getPointeeType()))
2367 return false;
2368
Douglas Gregorab209d82015-07-07 03:58:42 +00002369 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002370 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002371 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2372 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002373 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002374 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2375 FromObjCPtr->getPointeeType()))
2376 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002377 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002378 ToObjCPtr->getPointeeType(),
2379 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002380 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002381 return true;
2382 }
2383
2384 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2385 // Okay: this is some kind of implicit downcast of Objective-C
2386 // interfaces, which is permitted. However, we're going to
2387 // complain about it.
2388 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002389 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002390 ToObjCPtr->getPointeeType(),
2391 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002392 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002393 return true;
2394 }
Mike Stump11289f42009-09-09 15:08:12 +00002395 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002396 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002397 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002398 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002399 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002400 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002401 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002402 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002403 // to a block pointer type.
2404 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002405 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002406 return true;
2407 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002408 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002410 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002411 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002412 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002413 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002414 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002415 return true;
2416 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002417 else
Douglas Gregora119f102008-12-19 19:13:09 +00002418 return false;
2419
Douglas Gregor033f56d2008-12-23 00:53:59 +00002420 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002421 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002422 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002423 else if (const BlockPointerType *FromBlockPtr =
2424 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002425 FromPointeeType = FromBlockPtr->getPointeeType();
2426 else
Douglas Gregora119f102008-12-19 19:13:09 +00002427 return false;
2428
Douglas Gregora119f102008-12-19 19:13:09 +00002429 // If we have pointers to pointers, recursively check whether this
2430 // is an Objective-C conversion.
2431 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2432 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2433 IncompatibleObjC)) {
2434 // We always complain about this conversion.
2435 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002436 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002437 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002438 return true;
2439 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002440 // Allow conversion of pointee being objective-c pointer to another one;
2441 // as in I* to id.
2442 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2443 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2444 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2445 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002446
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002447 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002448 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002449 return true;
2450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002451
Douglas Gregor033f56d2008-12-23 00:53:59 +00002452 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002453 // differences in the argument and result types are in Objective-C
2454 // pointer conversions. If so, we permit the conversion (but
2455 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002456 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002457 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002458 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002459 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002460 if (FromFunctionType && ToFunctionType) {
2461 // If the function types are exactly the same, this isn't an
2462 // Objective-C pointer conversion.
2463 if (Context.getCanonicalType(FromPointeeType)
2464 == Context.getCanonicalType(ToPointeeType))
2465 return false;
2466
2467 // Perform the quick checks that will tell us whether these
2468 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002469 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002470 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2471 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2472 return false;
2473
2474 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002475 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2476 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002477 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002478 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2479 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002480 ConvertedType, IncompatibleObjC)) {
2481 // Okay, we have an Objective-C pointer conversion.
2482 HasObjCConversion = true;
2483 } else {
2484 // Function types are too different. Abort.
2485 return false;
2486 }
Mike Stump11289f42009-09-09 15:08:12 +00002487
Douglas Gregora119f102008-12-19 19:13:09 +00002488 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002489 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002490 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002491 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2492 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002493 if (Context.getCanonicalType(FromArgType)
2494 == Context.getCanonicalType(ToArgType)) {
2495 // Okay, the types match exactly. Nothing to do.
2496 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2497 ConvertedType, IncompatibleObjC)) {
2498 // Okay, we have an Objective-C pointer conversion.
2499 HasObjCConversion = true;
2500 } else {
2501 // Argument types are too different. Abort.
2502 return false;
2503 }
2504 }
2505
2506 if (HasObjCConversion) {
2507 // We had an Objective-C conversion. Allow this pointer
2508 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002509 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002510 IncompatibleObjC = true;
2511 return true;
2512 }
2513 }
2514
Sebastian Redl72b597d2009-01-25 19:43:20 +00002515 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002516}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002517
John McCall31168b02011-06-15 23:02:42 +00002518/// \brief Determine whether this is an Objective-C writeback conversion,
2519/// used for parameter passing when performing automatic reference counting.
2520///
2521/// \param FromType The type we're converting form.
2522///
2523/// \param ToType The type we're converting to.
2524///
2525/// \param ConvertedType The type that will be produced after applying
2526/// this conversion.
2527bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2528 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002529 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002530 Context.hasSameUnqualifiedType(FromType, ToType))
2531 return false;
2532
2533 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2534 QualType ToPointee;
2535 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2536 ToPointee = ToPointer->getPointeeType();
2537 else
2538 return false;
2539
2540 Qualifiers ToQuals = ToPointee.getQualifiers();
2541 if (!ToPointee->isObjCLifetimeType() ||
2542 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002543 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002544 return false;
2545
2546 // Argument must be a pointer to __strong to __weak.
2547 QualType FromPointee;
2548 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2549 FromPointee = FromPointer->getPointeeType();
2550 else
2551 return false;
2552
2553 Qualifiers FromQuals = FromPointee.getQualifiers();
2554 if (!FromPointee->isObjCLifetimeType() ||
2555 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2556 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2557 return false;
2558
2559 // Make sure that we have compatible qualifiers.
2560 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2561 if (!ToQuals.compatiblyIncludes(FromQuals))
2562 return false;
2563
2564 // Remove qualifiers from the pointee type we're converting from; they
2565 // aren't used in the compatibility check belong, and we'll be adding back
2566 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2567 FromPointee = FromPointee.getUnqualifiedType();
2568
2569 // The unqualified form of the pointee types must be compatible.
2570 ToPointee = ToPointee.getUnqualifiedType();
2571 bool IncompatibleObjC;
2572 if (Context.typesAreCompatible(FromPointee, ToPointee))
2573 FromPointee = ToPointee;
2574 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2575 IncompatibleObjC))
2576 return false;
2577
2578 /// \brief Construct the type we're converting to, which is a pointer to
2579 /// __autoreleasing pointee.
2580 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2581 ConvertedType = Context.getPointerType(FromPointee);
2582 return true;
2583}
2584
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002585bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2586 QualType& ConvertedType) {
2587 QualType ToPointeeType;
2588 if (const BlockPointerType *ToBlockPtr =
2589 ToType->getAs<BlockPointerType>())
2590 ToPointeeType = ToBlockPtr->getPointeeType();
2591 else
2592 return false;
2593
2594 QualType FromPointeeType;
2595 if (const BlockPointerType *FromBlockPtr =
2596 FromType->getAs<BlockPointerType>())
2597 FromPointeeType = FromBlockPtr->getPointeeType();
2598 else
2599 return false;
2600 // We have pointer to blocks, check whether the only
2601 // differences in the argument and result types are in Objective-C
2602 // pointer conversions. If so, we permit the conversion.
2603
2604 const FunctionProtoType *FromFunctionType
2605 = FromPointeeType->getAs<FunctionProtoType>();
2606 const FunctionProtoType *ToFunctionType
2607 = ToPointeeType->getAs<FunctionProtoType>();
2608
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002609 if (!FromFunctionType || !ToFunctionType)
2610 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002611
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002612 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002613 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002614
2615 // Perform the quick checks that will tell us whether these
2616 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002617 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002618 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2619 return false;
2620
2621 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2622 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2623 if (FromEInfo != ToEInfo)
2624 return false;
2625
2626 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002627 if (Context.hasSameType(FromFunctionType->getReturnType(),
2628 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002629 // Okay, the types match exactly. Nothing to do.
2630 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002631 QualType RHS = FromFunctionType->getReturnType();
2632 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002633 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002634 !RHS.hasQualifiers() && LHS.hasQualifiers())
2635 LHS = LHS.getUnqualifiedType();
2636
2637 if (Context.hasSameType(RHS,LHS)) {
2638 // OK exact match.
2639 } else if (isObjCPointerConversion(RHS, LHS,
2640 ConvertedType, IncompatibleObjC)) {
2641 if (IncompatibleObjC)
2642 return false;
2643 // Okay, we have an Objective-C pointer conversion.
2644 }
2645 else
2646 return false;
2647 }
2648
2649 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002650 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002651 ArgIdx != NumArgs; ++ArgIdx) {
2652 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002653 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2654 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002655 if (Context.hasSameType(FromArgType, ToArgType)) {
2656 // Okay, the types match exactly. Nothing to do.
2657 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2658 ConvertedType, IncompatibleObjC)) {
2659 if (IncompatibleObjC)
2660 return false;
2661 // Okay, we have an Objective-C pointer conversion.
2662 } else
2663 // Argument types are too different. Abort.
2664 return false;
2665 }
John McCall18afab72016-03-01 00:49:02 +00002666 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2667 ToFunctionType))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002668 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002669
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002670 ConvertedType = ToType;
2671 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002672}
2673
Richard Trieucaff2472011-11-23 22:32:32 +00002674enum {
2675 ft_default,
2676 ft_different_class,
2677 ft_parameter_arity,
2678 ft_parameter_mismatch,
2679 ft_return_type,
Richard Smith3c4f8d22016-10-16 17:54:23 +00002680 ft_qualifer_mismatch,
2681 ft_noexcept
Richard Trieucaff2472011-11-23 22:32:32 +00002682};
2683
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002684/// Attempts to get the FunctionProtoType from a Type. Handles
2685/// MemberFunctionPointers properly.
2686static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2687 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2688 return FPT;
2689
2690 if (auto *MPT = FromType->getAs<MemberPointerType>())
2691 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2692
2693 return nullptr;
2694}
2695
Richard Trieucaff2472011-11-23 22:32:32 +00002696/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2697/// function types. Catches different number of parameter, mismatch in
2698/// parameter types, and different return types.
2699void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2700 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002701 // If either type is not valid, include no extra info.
2702 if (FromType.isNull() || ToType.isNull()) {
2703 PDiag << ft_default;
2704 return;
2705 }
2706
Richard Trieucaff2472011-11-23 22:32:32 +00002707 // Get the function type from the pointers.
2708 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2709 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2710 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002711 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002712 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2713 << QualType(FromMember->getClass(), 0);
2714 return;
2715 }
2716 FromType = FromMember->getPointeeType();
2717 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002718 }
2719
Richard Trieu96ed5b62011-12-13 23:19:45 +00002720 if (FromType->isPointerType())
2721 FromType = FromType->getPointeeType();
2722 if (ToType->isPointerType())
2723 ToType = ToType->getPointeeType();
2724
2725 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002726 FromType = FromType.getNonReferenceType();
2727 ToType = ToType.getNonReferenceType();
2728
Richard Trieucaff2472011-11-23 22:32:32 +00002729 // Don't print extra info for non-specialized template functions.
2730 if (FromType->isInstantiationDependentType() &&
2731 !FromType->getAs<TemplateSpecializationType>()) {
2732 PDiag << ft_default;
2733 return;
2734 }
2735
Richard Trieu96ed5b62011-12-13 23:19:45 +00002736 // No extra info for same types.
2737 if (Context.hasSameType(FromType, ToType)) {
2738 PDiag << ft_default;
2739 return;
2740 }
2741
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002742 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2743 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002744
2745 // Both types need to be function types.
2746 if (!FromFunction || !ToFunction) {
2747 PDiag << ft_default;
2748 return;
2749 }
2750
Alp Toker9cacbab2014-01-20 20:26:09 +00002751 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2752 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2753 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002754 return;
2755 }
2756
2757 // Handle different parameter types.
2758 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002759 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002760 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002761 << ToFunction->getParamType(ArgPos)
2762 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002763 return;
2764 }
2765
2766 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002767 if (!Context.hasSameType(FromFunction->getReturnType(),
2768 ToFunction->getReturnType())) {
2769 PDiag << ft_return_type << ToFunction->getReturnType()
2770 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002771 return;
2772 }
2773
2774 unsigned FromQuals = FromFunction->getTypeQuals(),
2775 ToQuals = ToFunction->getTypeQuals();
2776 if (FromQuals != ToQuals) {
2777 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2778 return;
2779 }
2780
Richard Smith3c4f8d22016-10-16 17:54:23 +00002781 // Handle exception specification differences on canonical type (in C++17
2782 // onwards).
2783 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2784 ->isNothrow(Context) !=
2785 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2786 ->isNothrow(Context)) {
2787 PDiag << ft_noexcept;
2788 return;
2789 }
2790
Richard Trieucaff2472011-11-23 22:32:32 +00002791 // Unable to find a difference, so add no extra info.
2792 PDiag << ft_default;
2793}
2794
Alp Toker9cacbab2014-01-20 20:26:09 +00002795/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002796/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002797/// they have same number of arguments. If the parameters are different,
2798/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002799bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2800 const FunctionProtoType *NewType,
2801 unsigned *ArgPos) {
2802 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2803 N = NewType->param_type_begin(),
2804 E = OldType->param_type_end();
2805 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002806 if (!Context.hasSameType(O->getUnqualifiedType(),
2807 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002808 if (ArgPos)
2809 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002810 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002811 }
2812 }
2813 return true;
2814}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002815
Douglas Gregor39c16d42008-10-24 04:54:22 +00002816/// CheckPointerConversion - Check the pointer conversion from the
2817/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002818/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002819/// conversions for which IsPointerConversion has already returned
2820/// true. It returns true and produces a diagnostic if there was an
2821/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002822bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002823 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002824 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002825 bool IgnoreBaseAccess,
2826 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002827 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002828 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002829
John McCall8cb679e2010-11-15 09:13:47 +00002830 Kind = CK_BitCast;
2831
George Burgess IV60bc9722016-01-13 23:36:34 +00002832 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002833 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002834 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002835 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2836 DiagRuntimeBehavior(From->getExprLoc(), From,
2837 PDiag(diag::warn_impcast_bool_to_null_pointer)
2838 << ToType << From->getSourceRange());
2839 else if (!isUnevaluatedContext())
2840 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2841 << ToType << From->getSourceRange();
2842 }
John McCall9320b872011-09-09 05:25:32 +00002843 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2844 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002845 QualType FromPointeeType = FromPtrType->getPointeeType(),
2846 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002847
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002848 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2849 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002850 // We must have a derived-to-base conversion. Check an
2851 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002852 unsigned InaccessibleID = 0;
2853 unsigned AmbigiousID = 0;
2854 if (Diagnose) {
2855 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2856 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2857 }
2858 if (CheckDerivedToBaseConversion(
2859 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2860 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2861 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002862 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002863
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002864 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002865 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002866 }
David Majnemer6bf02822015-10-31 08:42:14 +00002867
George Burgess IV60bc9722016-01-13 23:36:34 +00002868 if (Diagnose && !IsCStyleOrFunctionalCast &&
2869 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002870 assert(getLangOpts().MSVCCompat &&
2871 "this should only be possible with MSVCCompat!");
2872 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2873 << From->getSourceRange();
2874 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002875 }
John McCall9320b872011-09-09 05:25:32 +00002876 } else if (const ObjCObjectPointerType *ToPtrType =
2877 ToType->getAs<ObjCObjectPointerType>()) {
2878 if (const ObjCObjectPointerType *FromPtrType =
2879 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002880 // Objective-C++ conversions are always okay.
2881 // FIXME: We should have a different class of conversions for the
2882 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002883 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002884 return false;
John McCall9320b872011-09-09 05:25:32 +00002885 } else if (FromType->isBlockPointerType()) {
2886 Kind = CK_BlockPointerToObjCPointerCast;
2887 } else {
2888 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002889 }
John McCall9320b872011-09-09 05:25:32 +00002890 } else if (ToType->isBlockPointerType()) {
2891 if (!FromType->isBlockPointerType())
2892 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002893 }
John McCall8cb679e2010-11-15 09:13:47 +00002894
2895 // We shouldn't fall into this case unless it's valid for other
2896 // reasons.
2897 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2898 Kind = CK_NullToPointer;
2899
Douglas Gregor39c16d42008-10-24 04:54:22 +00002900 return false;
2901}
2902
Sebastian Redl72b597d2009-01-25 19:43:20 +00002903/// IsMemberPointerConversion - Determines whether the conversion of the
2904/// expression From, which has the (possibly adjusted) type FromType, can be
2905/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2906/// If so, returns true and places the converted type (that might differ from
2907/// ToType in its cv-qualifiers at some level) into ConvertedType.
2908bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002909 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002910 bool InOverloadResolution,
2911 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002912 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002913 if (!ToTypePtr)
2914 return false;
2915
2916 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002917 if (From->isNullPointerConstant(Context,
2918 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2919 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002920 ConvertedType = ToType;
2921 return true;
2922 }
2923
2924 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002925 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002926 if (!FromTypePtr)
2927 return false;
2928
2929 // A pointer to member of B can be converted to a pointer to member of D,
2930 // where D is derived from B (C++ 4.11p2).
2931 QualType FromClass(FromTypePtr->getClass(), 0);
2932 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002933
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002934 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002935 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002936 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2937 ToClass.getTypePtr());
2938 return true;
2939 }
2940
2941 return false;
2942}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002943
Sebastian Redl72b597d2009-01-25 19:43:20 +00002944/// CheckMemberPointerConversion - Check the member pointer conversion from the
2945/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002946/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002947/// for which IsMemberPointerConversion has already returned true. It returns
2948/// true and produces a diagnostic if there was an error, or returns false
2949/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002950bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002951 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002952 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002953 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002954 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002955 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002956 if (!FromPtrType) {
2957 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002958 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002959 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002960 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002961 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002962 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002963 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002964
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002965 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002966 assert(ToPtrType && "No member pointer cast has a target type "
2967 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002968
Sebastian Redled8f2002009-01-28 18:33:18 +00002969 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2970 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002971
Sebastian Redled8f2002009-01-28 18:33:18 +00002972 // FIXME: What about dependent types?
2973 assert(FromClass->isRecordType() && "Pointer into non-class.");
2974 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002975
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002976 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002977 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002978 bool DerivationOkay =
2979 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002980 assert(DerivationOkay &&
2981 "Should not have been called if derivation isn't OK.");
2982 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002983
Sebastian Redled8f2002009-01-28 18:33:18 +00002984 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2985 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002986 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2987 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2988 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2989 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002990 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002991
Douglas Gregor89ee6822009-02-28 01:32:25 +00002992 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002993 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2994 << FromClass << ToClass << QualType(VBase, 0)
2995 << From->getSourceRange();
2996 return true;
2997 }
2998
John McCall5b0829a2010-02-10 09:31:12 +00002999 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00003000 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3001 Paths.front(),
3002 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00003003
Anders Carlssond7923c62009-08-22 23:33:40 +00003004 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00003005 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00003006 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00003007 return false;
3008}
3009
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003010/// Determine whether the lifetime conversion between the two given
3011/// qualifiers sets is nontrivial.
3012static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3013 Qualifiers ToQuals) {
3014 // Converting anything to const __unsafe_unretained is trivial.
3015 if (ToQuals.hasConst() &&
3016 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3017 return false;
3018
3019 return true;
3020}
3021
Douglas Gregor9a657932008-10-21 23:43:52 +00003022/// IsQualificationConversion - Determines whether the conversion from
3023/// an rvalue of type FromType to ToType is a qualification conversion
3024/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00003025///
3026/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3027/// when the qualification conversion involves a change in the Objective-C
3028/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00003029bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003030Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00003031 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003032 FromType = Context.getCanonicalType(FromType);
3033 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00003034 ObjCLifetimeConversion = false;
3035
Douglas Gregor9a657932008-10-21 23:43:52 +00003036 // If FromType and ToType are the same type, this is not a
3037 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00003038 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00003039 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00003040
Douglas Gregor9a657932008-10-21 23:43:52 +00003041 // (C++ 4.4p4):
3042 // A conversion can add cv-qualifiers at levels other than the first
3043 // in multi-level pointers, subject to the following rules: [...]
3044 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003045 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003046 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00003047 // Within each iteration of the loop, we check the qualifiers to
3048 // determine if this still looks like a qualification
3049 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003050 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00003051 // until there are no more pointers or pointers-to-members left to
3052 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003053 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00003054
Douglas Gregor90609aa2011-04-25 18:40:17 +00003055 Qualifiers FromQuals = FromType.getQualifiers();
3056 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00003057
3058 // Ignore __unaligned qualifier if this type is void.
3059 if (ToType.getUnqualifiedType()->isVoidType())
3060 FromQuals.removeUnaligned();
Douglas Gregor90609aa2011-04-25 18:40:17 +00003061
John McCall31168b02011-06-15 23:02:42 +00003062 // Objective-C ARC:
3063 // Check Objective-C lifetime conversions.
3064 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3065 UnwrappedAnyPointer) {
3066 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003067 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3068 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00003069 FromQuals.removeObjCLifetime();
3070 ToQuals.removeObjCLifetime();
3071 } else {
3072 // Qualification conversions cannot cast between different
3073 // Objective-C lifetime qualifiers.
3074 return false;
3075 }
3076 }
3077
Douglas Gregorf30053d2011-05-08 06:09:53 +00003078 // Allow addition/removal of GC attributes but not changing GC attributes.
3079 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3080 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3081 FromQuals.removeObjCGCAttr();
3082 ToQuals.removeObjCGCAttr();
3083 }
3084
Douglas Gregor9a657932008-10-21 23:43:52 +00003085 // -- for every j > 0, if const is in cv 1,j then const is in cv
3086 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003087 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003088 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003089
Douglas Gregor9a657932008-10-21 23:43:52 +00003090 // -- if the cv 1,j and cv 2,j are different, then const is in
3091 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003092 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003093 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003094 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003095
Douglas Gregor9a657932008-10-21 23:43:52 +00003096 // Keep track of whether all prior cv-qualifiers in the "to" type
3097 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003098 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003099 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003100 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003101
3102 // We are left with FromType and ToType being the pointee types
3103 // after unwrapping the original FromType and ToType the same number
3104 // of types. If we unwrapped any pointers, and if FromType and
3105 // ToType have the same unqualified type (since we checked
3106 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003107 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003108}
3109
Douglas Gregorc79862f2012-04-12 17:51:55 +00003110/// \brief - Determine whether this is a conversion from a scalar type to an
3111/// atomic type.
3112///
3113/// If successful, updates \c SCS's second and third steps in the conversion
3114/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003115static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3116 bool InOverloadResolution,
3117 StandardConversionSequence &SCS,
3118 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003119 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3120 if (!ToAtomic)
3121 return false;
3122
3123 StandardConversionSequence InnerSCS;
3124 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3125 InOverloadResolution, InnerSCS,
3126 CStyle, /*AllowObjCWritebackConversion=*/false))
3127 return false;
3128
3129 SCS.Second = InnerSCS.Second;
3130 SCS.setToType(1, InnerSCS.getToType(1));
3131 SCS.Third = InnerSCS.Third;
3132 SCS.QualificationIncludesObjCLifetime
3133 = InnerSCS.QualificationIncludesObjCLifetime;
3134 SCS.setToType(2, InnerSCS.getToType(2));
3135 return true;
3136}
3137
Sebastian Redle5417162012-03-27 18:33:03 +00003138static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3139 CXXConstructorDecl *Constructor,
3140 QualType Type) {
3141 const FunctionProtoType *CtorType =
3142 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003143 if (CtorType->getNumParams() > 0) {
3144 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003145 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3146 return true;
3147 }
3148 return false;
3149}
3150
Sebastian Redl82ace982012-02-11 23:51:08 +00003151static OverloadingResult
3152IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3153 CXXRecordDecl *To,
3154 UserDefinedConversionSequence &User,
3155 OverloadCandidateSet &CandidateSet,
3156 bool AllowExplicit) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003157 for (auto *D : S.LookupConstructors(To)) {
3158 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003159 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003160 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003161
Richard Smithc2bebe92016-05-11 20:37:46 +00003162 bool Usable = !Info.Constructor->isInvalidDecl() &&
3163 S.isInitListConstructor(Info.Constructor) &&
3164 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003165 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003166 // If the first argument is (a reference to) the target type,
3167 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003168 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3169 S.Context, Info.Constructor, ToType);
3170 if (Info.ConstructorTmpl)
3171 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3172 /*ExplicitArgs*/ nullptr, From,
3173 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003174 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003175 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3176 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003177 }
3178 }
3179
3180 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3181
3182 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003183 switch (auto Result =
3184 CandidateSet.BestViableFunction(S, From->getLocStart(),
3185 Best, true)) {
3186 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003187 case OR_Success: {
3188 // Record the standard conversion we used and the conversion function.
3189 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003190 QualType ThisType = Constructor->getThisType(S.Context);
3191 // Initializer lists don't have conversions as such.
3192 User.Before.setAsIdentityConversion();
3193 User.HadMultipleCandidates = HadMultipleCandidates;
3194 User.ConversionFunction = Constructor;
3195 User.FoundConversionFunction = Best->FoundDecl;
3196 User.After.setAsIdentityConversion();
3197 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3198 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003199 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003200 }
3201
3202 case OR_No_Viable_Function:
3203 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003204 case OR_Ambiguous:
3205 return OR_Ambiguous;
3206 }
3207
3208 llvm_unreachable("Invalid OverloadResult!");
3209}
3210
Douglas Gregor576e98c2009-01-30 23:27:23 +00003211/// Determines whether there is a user-defined conversion sequence
3212/// (C++ [over.ics.user]) that converts expression From to the type
3213/// ToType. If such a conversion exists, User will contain the
3214/// user-defined conversion sequence that performs such a conversion
3215/// and this routine will return true. Otherwise, this routine returns
3216/// false and User is unspecified.
3217///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003218/// \param AllowExplicit true if the conversion should consider C++0x
3219/// "explicit" conversion functions as well as non-explicit conversion
3220/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003221///
3222/// \param AllowObjCConversionOnExplicit true if the conversion should
3223/// allow an extra Objective-C pointer conversion on uses of explicit
3224/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003225static OverloadingResult
3226IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003227 UserDefinedConversionSequence &User,
3228 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003229 bool AllowExplicit,
3230 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003231 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003232
Douglas Gregor5ab11652010-04-17 22:01:05 +00003233 // Whether we will only visit constructors.
3234 bool ConstructorsOnly = false;
3235
3236 // If the type we are conversion to is a class type, enumerate its
3237 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003238 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003239 // C++ [over.match.ctor]p1:
3240 // When objects of class type are direct-initialized (8.5), or
3241 // copy-initialized from an expression of the same or a
3242 // derived class type (8.5), overload resolution selects the
3243 // constructor. [...] For copy-initialization, the candidate
3244 // functions are all the converting constructors (12.3.1) of
3245 // that class. The argument list is the expression-list within
3246 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003247 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003248 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003249 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003250 ConstructorsOnly = true;
3251
Richard Smithdb0ac552015-12-18 22:40:25 +00003252 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003253 // We're not going to find any constructors.
3254 } else if (CXXRecordDecl *ToRecordDecl
3255 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003256
3257 Expr **Args = &From;
3258 unsigned NumArgs = 1;
3259 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003260 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003261 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003262 OverloadingResult Result = IsInitializerListConstructorConversion(
3263 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3264 if (Result != OR_No_Viable_Function)
3265 return Result;
3266 // Never mind.
3267 CandidateSet.clear();
3268
3269 // If we're list-initializing, we pass the individual elements as
3270 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003271 Args = InitList->getInits();
3272 NumArgs = InitList->getNumInits();
3273 ListInitializing = true;
3274 }
3275
Richard Smithc2bebe92016-05-11 20:37:46 +00003276 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3277 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003278 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003279 continue;
John McCalla0296f72010-03-19 07:35:19 +00003280
Richard Smithc2bebe92016-05-11 20:37:46 +00003281 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003282 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003283 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003284 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003285 Usable = Usable &&
3286 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003287 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003288 bool SuppressUserConversions = !ConstructorsOnly;
3289 if (SuppressUserConversions && ListInitializing) {
3290 SuppressUserConversions = false;
3291 if (NumArgs == 1) {
3292 // If the first argument is (a reference to) the target type,
3293 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003294 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003295 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003296 }
3297 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003298 if (Info.ConstructorTmpl)
3299 S.AddTemplateOverloadCandidate(
3300 Info.ConstructorTmpl, Info.FoundDecl,
3301 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3302 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003303 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003304 // Allow one user-defined conversion when user specifies a
3305 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003306 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003307 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003308 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003309 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003310 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003311 }
3312 }
3313
Douglas Gregor5ab11652010-04-17 22:01:05 +00003314 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003315 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003316 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003317 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003318 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003319 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003320 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003321 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3322 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003323 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3324 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003325 DeclAccessPair FoundDecl = I.getPair();
3326 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003327 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3328 if (isa<UsingShadowDecl>(D))
3329 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3330
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003331 CXXConversionDecl *Conv;
3332 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003333 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3334 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003335 else
John McCallda4458e2010-03-31 01:36:47 +00003336 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003337
3338 if (AllowExplicit || !Conv->isExplicit()) {
3339 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003340 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3341 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003342 CandidateSet,
3343 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003344 else
John McCall5c32be02010-08-24 20:38:10 +00003345 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003346 From, ToType, CandidateSet,
3347 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003348 }
3349 }
3350 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003351 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003352
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003353 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3354
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003355 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003356 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3357 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003358 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003359 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003360 // Record the standard conversion we used and the conversion function.
3361 if (CXXConstructorDecl *Constructor
3362 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3363 // C++ [over.ics.user]p1:
3364 // If the user-defined conversion is specified by a
3365 // constructor (12.3.1), the initial standard conversion
3366 // sequence converts the source type to the type required by
3367 // the argument of the constructor.
3368 //
3369 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003370 if (isa<InitListExpr>(From)) {
3371 // Initializer lists don't have conversions as such.
3372 User.Before.setAsIdentityConversion();
3373 } else {
3374 if (Best->Conversions[0].isEllipsis())
3375 User.EllipsisConversion = true;
3376 else {
3377 User.Before = Best->Conversions[0].Standard;
3378 User.EllipsisConversion = false;
3379 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003380 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003381 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003382 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003383 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003384 User.After.setAsIdentityConversion();
3385 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3386 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003387 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003388 }
3389 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003390 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3391 // C++ [over.ics.user]p1:
3392 //
3393 // [...] If the user-defined conversion is specified by a
3394 // conversion function (12.3.2), the initial standard
3395 // conversion sequence converts the source type to the
3396 // implicit object parameter of the conversion function.
3397 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003398 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003399 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003400 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003401 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003402
John McCall5c32be02010-08-24 20:38:10 +00003403 // C++ [over.ics.user]p2:
3404 // The second standard conversion sequence converts the
3405 // result of the user-defined conversion to the target type
3406 // for the sequence. Since an implicit conversion sequence
3407 // is an initialization, the special rules for
3408 // initialization by user-defined conversion apply when
3409 // selecting the best user-defined conversion for a
3410 // user-defined conversion sequence (see 13.3.3 and
3411 // 13.3.3.1).
3412 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003413 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003414 }
David Blaikie8a40f702012-01-17 06:56:22 +00003415 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003416
John McCall5c32be02010-08-24 20:38:10 +00003417 case OR_No_Viable_Function:
3418 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
John McCall5c32be02010-08-24 20:38:10 +00003420 case OR_Ambiguous:
3421 return OR_Ambiguous;
3422 }
3423
David Blaikie8a40f702012-01-17 06:56:22 +00003424 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003425}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003426
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003427bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003428Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003429 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003430 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3431 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003432 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003433 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003434 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003435 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003436 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3437 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003438 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003439 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003440 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003441 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003442 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003443 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003444 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003445 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003446 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003447 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003448}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003449
Douglas Gregor2837aa22012-02-22 17:32:19 +00003450/// \brief Compare the user-defined conversion functions or constructors
3451/// of two user-defined conversion sequences to determine whether any ordering
3452/// is possible.
3453static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003454compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003455 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003456 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003457 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003458
Douglas Gregor2837aa22012-02-22 17:32:19 +00003459 // Objective-C++:
3460 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003461 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003462 // respectively, always prefer the conversion to a function pointer,
3463 // because the function pointer is more lightweight and is more likely
3464 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003465 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003466 if (!Conv1)
3467 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003468
Douglas Gregor2837aa22012-02-22 17:32:19 +00003469 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3470 if (!Conv2)
3471 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003472
Douglas Gregor2837aa22012-02-22 17:32:19 +00003473 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3474 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3475 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3476 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003477 return Block1 ? ImplicitConversionSequence::Worse
3478 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003479 }
3480
3481 return ImplicitConversionSequence::Indistinguishable;
3482}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003483
3484static bool hasDeprecatedStringLiteralToCharPtrConversion(
3485 const ImplicitConversionSequence &ICS) {
3486 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3487 (ICS.isUserDefined() &&
3488 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3489}
3490
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003491/// CompareImplicitConversionSequences - Compare two implicit
3492/// conversion sequences to determine whether one is better than the
3493/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003494static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003495CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003496 const ImplicitConversionSequence& ICS1,
3497 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003498{
3499 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3500 // conversion sequences (as defined in 13.3.3.1)
3501 // -- a standard conversion sequence (13.3.3.1.1) is a better
3502 // conversion sequence than a user-defined conversion sequence or
3503 // an ellipsis conversion sequence, and
3504 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3505 // conversion sequence than an ellipsis conversion sequence
3506 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003507 //
John McCall0d1da222010-01-12 00:44:57 +00003508 // C++0x [over.best.ics]p10:
3509 // For the purpose of ranking implicit conversion sequences as
3510 // described in 13.3.3.2, the ambiguous conversion sequence is
3511 // treated as a user-defined sequence that is indistinguishable
3512 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003513
3514 // String literal to 'char *' conversion has been deprecated in C++03. It has
3515 // been removed from C++11. We still accept this conversion, if it happens at
3516 // the best viable function. Otherwise, this conversion is considered worse
3517 // than ellipsis conversion. Consider this as an extension; this is not in the
3518 // standard. For example:
3519 //
3520 // int &f(...); // #1
3521 // void f(char*); // #2
3522 // void g() { int &r = f("foo"); }
3523 //
3524 // In C++03, we pick #2 as the best viable function.
3525 // In C++11, we pick #1 as the best viable function, because ellipsis
3526 // conversion is better than string-literal to char* conversion (since there
3527 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3528 // convert arguments, #2 would be the best viable function in C++11.
3529 // If the best viable function has this conversion, a warning will be issued
3530 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3531
3532 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3533 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3534 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3535 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3536 ? ImplicitConversionSequence::Worse
3537 : ImplicitConversionSequence::Better;
3538
Douglas Gregor5ab11652010-04-17 22:01:05 +00003539 if (ICS1.getKindRank() < ICS2.getKindRank())
3540 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003541 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003542 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003543
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003544 // The following checks require both conversion sequences to be of
3545 // the same kind.
3546 if (ICS1.getKind() != ICS2.getKind())
3547 return ImplicitConversionSequence::Indistinguishable;
3548
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003549 ImplicitConversionSequence::CompareKind Result =
3550 ImplicitConversionSequence::Indistinguishable;
3551
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003552 // Two implicit conversion sequences of the same form are
3553 // indistinguishable conversion sequences unless one of the
3554 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003555
3556 // List-initialization sequence L1 is a better conversion sequence than
3557 // list-initialization sequence L2 if:
3558 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3559 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003560 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003561 // and N1 is smaller than N2.,
3562 // even if one of the other rules in this paragraph would otherwise apply.
3563 if (!ICS1.isBad()) {
3564 if (ICS1.isStdInitializerListElement() &&
3565 !ICS2.isStdInitializerListElement())
3566 return ImplicitConversionSequence::Better;
3567 if (!ICS1.isStdInitializerListElement() &&
3568 ICS2.isStdInitializerListElement())
3569 return ImplicitConversionSequence::Worse;
3570 }
3571
John McCall0d1da222010-01-12 00:44:57 +00003572 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003573 // Standard conversion sequence S1 is a better conversion sequence than
3574 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003575 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003576 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003577 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003578 // User-defined conversion sequence U1 is a better conversion
3579 // sequence than another user-defined conversion sequence U2 if
3580 // they contain the same user-defined conversion function or
3581 // constructor and if the second standard conversion sequence of
3582 // U1 is better than the second standard conversion sequence of
3583 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003584 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003585 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003586 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003587 ICS1.UserDefined.After,
3588 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003589 else
3590 Result = compareConversionFunctions(S,
3591 ICS1.UserDefined.ConversionFunction,
3592 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003593 }
3594
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003595 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003596}
3597
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003598static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3599 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3600 Qualifiers Quals;
3601 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003604
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003605 return Context.hasSameUnqualifiedType(T1, T2);
3606}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003607
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003608// Per 13.3.3.2p3, compare the given standard conversion sequences to
3609// determine if one is a proper subset of the other.
3610static ImplicitConversionSequence::CompareKind
3611compareStandardConversionSubsets(ASTContext &Context,
3612 const StandardConversionSequence& SCS1,
3613 const StandardConversionSequence& SCS2) {
3614 ImplicitConversionSequence::CompareKind Result
3615 = ImplicitConversionSequence::Indistinguishable;
3616
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003617 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003618 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003619 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3620 return ImplicitConversionSequence::Better;
3621 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3622 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003623
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003624 if (SCS1.Second != SCS2.Second) {
3625 if (SCS1.Second == ICK_Identity)
3626 Result = ImplicitConversionSequence::Better;
3627 else if (SCS2.Second == ICK_Identity)
3628 Result = ImplicitConversionSequence::Worse;
3629 else
3630 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003631 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003632 return ImplicitConversionSequence::Indistinguishable;
3633
3634 if (SCS1.Third == SCS2.Third) {
3635 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3636 : ImplicitConversionSequence::Indistinguishable;
3637 }
3638
3639 if (SCS1.Third == ICK_Identity)
3640 return Result == ImplicitConversionSequence::Worse
3641 ? ImplicitConversionSequence::Indistinguishable
3642 : ImplicitConversionSequence::Better;
3643
3644 if (SCS2.Third == ICK_Identity)
3645 return Result == ImplicitConversionSequence::Better
3646 ? ImplicitConversionSequence::Indistinguishable
3647 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003648
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003649 return ImplicitConversionSequence::Indistinguishable;
3650}
3651
Douglas Gregore696ebb2011-01-26 14:52:12 +00003652/// \brief Determine whether one of the given reference bindings is better
3653/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003654static bool
3655isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3656 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003657 // C++0x [over.ics.rank]p3b4:
3658 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3659 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003660 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003661 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003662 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003663 // reference*.
3664 //
3665 // FIXME: Rvalue references. We're going rogue with the above edits,
3666 // because the semantics in the current C++0x working paper (N3225 at the
3667 // time of this writing) break the standard definition of std::forward
3668 // and std::reference_wrapper when dealing with references to functions.
3669 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003670 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3671 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3672 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003673
Douglas Gregore696ebb2011-01-26 14:52:12 +00003674 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3675 SCS2.IsLvalueReference) ||
3676 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003677 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003678}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003679
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003680/// CompareStandardConversionSequences - Compare two standard
3681/// conversion sequences to determine whether one is better than the
3682/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003683static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003684CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003685 const StandardConversionSequence& SCS1,
3686 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003687{
3688 // Standard conversion sequence S1 is a better conversion sequence
3689 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3690
3691 // -- S1 is a proper subsequence of S2 (comparing the conversion
3692 // sequences in the canonical form defined by 13.3.3.1.1,
3693 // excluding any Lvalue Transformation; the identity conversion
3694 // sequence is considered to be a subsequence of any
3695 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003696 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003697 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003698 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003699
3700 // -- the rank of S1 is better than the rank of S2 (by the rules
3701 // defined below), or, if not that,
3702 ImplicitConversionRank Rank1 = SCS1.getRank();
3703 ImplicitConversionRank Rank2 = SCS2.getRank();
3704 if (Rank1 < Rank2)
3705 return ImplicitConversionSequence::Better;
3706 else if (Rank2 < Rank1)
3707 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003708
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003709 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3710 // are indistinguishable unless one of the following rules
3711 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003712
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003713 // A conversion that is not a conversion of a pointer, or
3714 // pointer to member, to bool is better than another conversion
3715 // that is such a conversion.
3716 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3717 return SCS2.isPointerConversionToBool()
3718 ? ImplicitConversionSequence::Better
3719 : ImplicitConversionSequence::Worse;
3720
Douglas Gregor5c407d92008-10-23 00:40:37 +00003721 // C++ [over.ics.rank]p4b2:
3722 //
3723 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003724 // conversion of B* to A* is better than conversion of B* to
3725 // void*, and conversion of A* to void* is better than conversion
3726 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003727 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003728 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003729 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003730 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003731 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3732 // Exactly one of the conversion sequences is a conversion to
3733 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003734 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3735 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003736 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3737 // Neither conversion sequence converts to a void pointer; compare
3738 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003739 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003740 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003741 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003742 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3743 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003744 // Both conversion sequences are conversions to void
3745 // pointers. Compare the source types to determine if there's an
3746 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003747 QualType FromType1 = SCS1.getFromType();
3748 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003749
3750 // Adjust the types we're converting from via the array-to-pointer
3751 // conversion, if we need to.
3752 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003753 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003754 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003755 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003756
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003757 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3758 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003759
Richard Smith0f59cb32015-12-18 21:45:41 +00003760 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003761 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003762 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003763 return ImplicitConversionSequence::Worse;
3764
3765 // Objective-C++: If one interface is more specific than the
3766 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003767 const ObjCObjectPointerType* FromObjCPtr1
3768 = FromType1->getAs<ObjCObjectPointerType>();
3769 const ObjCObjectPointerType* FromObjCPtr2
3770 = FromType2->getAs<ObjCObjectPointerType>();
3771 if (FromObjCPtr1 && FromObjCPtr2) {
3772 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3773 FromObjCPtr2);
3774 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3775 FromObjCPtr1);
3776 if (AssignLeft != AssignRight) {
3777 return AssignLeft? ImplicitConversionSequence::Better
3778 : ImplicitConversionSequence::Worse;
3779 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003780 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003781 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003782
3783 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3784 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003785 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003786 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003787 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003788
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003789 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003790 // Check for a better reference binding based on the kind of bindings.
3791 if (isBetterReferenceBindingKind(SCS1, SCS2))
3792 return ImplicitConversionSequence::Better;
3793 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3794 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795
Sebastian Redlb28b4072009-03-22 23:49:27 +00003796 // C++ [over.ics.rank]p3b4:
3797 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3798 // which the references refer are the same type except for
3799 // top-level cv-qualifiers, and the type to which the reference
3800 // initialized by S2 refers is more cv-qualified than the type
3801 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003802 QualType T1 = SCS1.getToType(2);
3803 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003804 T1 = S.Context.getCanonicalType(T1);
3805 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003806 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003807 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3808 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003809 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003810 // Objective-C++ ARC: If the references refer to objects with different
3811 // lifetimes, prefer bindings that don't change lifetime.
3812 if (SCS1.ObjCLifetimeConversionBinding !=
3813 SCS2.ObjCLifetimeConversionBinding) {
3814 return SCS1.ObjCLifetimeConversionBinding
3815 ? ImplicitConversionSequence::Worse
3816 : ImplicitConversionSequence::Better;
3817 }
3818
Chandler Carruth8e543b32010-12-12 08:17:55 +00003819 // If the type is an array type, promote the element qualifiers to the
3820 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003821 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003822 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003823 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003824 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003825 if (T2.isMoreQualifiedThan(T1))
3826 return ImplicitConversionSequence::Better;
3827 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003828 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003829 }
3830 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003831
Francois Pichet08d2fa02011-09-18 21:37:37 +00003832 // In Microsoft mode, prefer an integral conversion to a
3833 // floating-to-integral conversion if the integral conversion
3834 // is between types of the same size.
3835 // For example:
3836 // void f(float);
3837 // void f(int);
3838 // int main {
3839 // long a;
3840 // f(a);
3841 // }
3842 // Here, MSVC will call f(int) instead of generating a compile error
3843 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003844 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3845 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003846 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003847 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003848 return ImplicitConversionSequence::Better;
3849
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003850 return ImplicitConversionSequence::Indistinguishable;
3851}
3852
3853/// CompareQualificationConversions - Compares two standard conversion
3854/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003855/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003856static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003857CompareQualificationConversions(Sema &S,
3858 const StandardConversionSequence& SCS1,
3859 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003860 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003861 // -- S1 and S2 differ only in their qualification conversion and
3862 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3863 // cv-qualification signature of type T1 is a proper subset of
3864 // the cv-qualification signature of type T2, and S1 is not the
3865 // deprecated string literal array-to-pointer conversion (4.2).
3866 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3867 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3868 return ImplicitConversionSequence::Indistinguishable;
3869
3870 // FIXME: the example in the standard doesn't use a qualification
3871 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003872 QualType T1 = SCS1.getToType(2);
3873 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003874 T1 = S.Context.getCanonicalType(T1);
3875 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003876 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003877 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3878 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003879
3880 // If the types are the same, we won't learn anything by unwrapped
3881 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003882 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003883 return ImplicitConversionSequence::Indistinguishable;
3884
Chandler Carruth607f38e2009-12-29 07:16:59 +00003885 // If the type is an array type, promote the element qualifiers to the type
3886 // for comparison.
3887 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003888 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003889 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003890 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003891
Mike Stump11289f42009-09-09 15:08:12 +00003892 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003893 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003894
3895 // Objective-C++ ARC:
3896 // Prefer qualification conversions not involving a change in lifetime
3897 // to qualification conversions that do not change lifetime.
3898 if (SCS1.QualificationIncludesObjCLifetime !=
3899 SCS2.QualificationIncludesObjCLifetime) {
3900 Result = SCS1.QualificationIncludesObjCLifetime
3901 ? ImplicitConversionSequence::Worse
3902 : ImplicitConversionSequence::Better;
3903 }
3904
John McCall5c32be02010-08-24 20:38:10 +00003905 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003906 // Within each iteration of the loop, we check the qualifiers to
3907 // determine if this still looks like a qualification
3908 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003909 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003910 // until there are no more pointers or pointers-to-members left
3911 // to unwrap. This essentially mimics what
3912 // IsQualificationConversion does, but here we're checking for a
3913 // strict subset of qualifiers.
3914 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3915 // The qualifiers are the same, so this doesn't tell us anything
3916 // about how the sequences rank.
3917 ;
3918 else if (T2.isMoreQualifiedThan(T1)) {
3919 // T1 has fewer qualifiers, so it could be the better sequence.
3920 if (Result == ImplicitConversionSequence::Worse)
3921 // Neither has qualifiers that are a subset of the other's
3922 // qualifiers.
3923 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003924
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003925 Result = ImplicitConversionSequence::Better;
3926 } else if (T1.isMoreQualifiedThan(T2)) {
3927 // T2 has fewer qualifiers, so it could be the better sequence.
3928 if (Result == ImplicitConversionSequence::Better)
3929 // Neither has qualifiers that are a subset of the other's
3930 // qualifiers.
3931 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003932
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003933 Result = ImplicitConversionSequence::Worse;
3934 } else {
3935 // Qualifiers are disjoint.
3936 return ImplicitConversionSequence::Indistinguishable;
3937 }
3938
3939 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003940 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003941 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003942 }
3943
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003944 // Check that the winning standard conversion sequence isn't using
3945 // the deprecated string literal array to pointer conversion.
3946 switch (Result) {
3947 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003948 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003949 Result = ImplicitConversionSequence::Indistinguishable;
3950 break;
3951
3952 case ImplicitConversionSequence::Indistinguishable:
3953 break;
3954
3955 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003956 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003957 Result = ImplicitConversionSequence::Indistinguishable;
3958 break;
3959 }
3960
3961 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003962}
3963
Douglas Gregor5c407d92008-10-23 00:40:37 +00003964/// CompareDerivedToBaseConversions - Compares two standard conversion
3965/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003966/// various kinds of derived-to-base conversions (C++
3967/// [over.ics.rank]p4b3). As part of these checks, we also look at
3968/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003969static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003970CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003971 const StandardConversionSequence& SCS1,
3972 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003973 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003974 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003975 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003976 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003977
3978 // Adjust the types we're converting from via the array-to-pointer
3979 // conversion, if we need to.
3980 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003981 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003982 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003983 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003984
3985 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003986 FromType1 = S.Context.getCanonicalType(FromType1);
3987 ToType1 = S.Context.getCanonicalType(ToType1);
3988 FromType2 = S.Context.getCanonicalType(FromType2);
3989 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003990
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003991 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003992 //
3993 // If class B is derived directly or indirectly from class A and
3994 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003995 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003996 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003997 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003998 SCS2.Second == ICK_Pointer_Conversion &&
3999 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4000 FromType1->isPointerType() && FromType2->isPointerType() &&
4001 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004002 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004003 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00004004 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004005 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004006 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004007 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00004008 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004009 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00004010
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004011 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00004012 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004013 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004014 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004015 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00004016 return ImplicitConversionSequence::Worse;
4017 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004018
4019 // -- conversion of B* to A* is better than conversion of C* to A*,
4020 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004021 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004022 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004023 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004024 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00004025 }
4026 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4027 SCS2.Second == ICK_Pointer_Conversion) {
4028 const ObjCObjectPointerType *FromPtr1
4029 = FromType1->getAs<ObjCObjectPointerType>();
4030 const ObjCObjectPointerType *FromPtr2
4031 = FromType2->getAs<ObjCObjectPointerType>();
4032 const ObjCObjectPointerType *ToPtr1
4033 = ToType1->getAs<ObjCObjectPointerType>();
4034 const ObjCObjectPointerType *ToPtr2
4035 = ToType2->getAs<ObjCObjectPointerType>();
4036
4037 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4038 // Apply the same conversion ranking rules for Objective-C pointer types
4039 // that we do for C++ pointers to class types. However, we employ the
4040 // Objective-C pseudo-subtyping relationship used for assignment of
4041 // Objective-C pointer types.
4042 bool FromAssignLeft
4043 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4044 bool FromAssignRight
4045 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4046 bool ToAssignLeft
4047 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4048 bool ToAssignRight
4049 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
Alex Lorenza9832132017-04-06 13:06:34 +00004050
Douglas Gregor058d3de2011-01-31 18:51:41 +00004051 // A conversion to an a non-id object pointer type or qualified 'id'
4052 // type is better than a conversion to 'id'.
4053 if (ToPtr1->isObjCIdType() &&
4054 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4055 return ImplicitConversionSequence::Worse;
4056 if (ToPtr2->isObjCIdType() &&
4057 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4058 return ImplicitConversionSequence::Better;
4059
4060 // A conversion to a non-id object pointer type is better than a
4061 // conversion to a qualified 'id' type
4062 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4063 return ImplicitConversionSequence::Worse;
4064 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4065 return ImplicitConversionSequence::Better;
4066
4067 // A conversion to an a non-Class object pointer type or qualified 'Class'
4068 // type is better than a conversion to 'Class'.
4069 if (ToPtr1->isObjCClassType() &&
4070 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4071 return ImplicitConversionSequence::Worse;
4072 if (ToPtr2->isObjCClassType() &&
4073 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4074 return ImplicitConversionSequence::Better;
4075
4076 // A conversion to a non-Class object pointer type is better than a
4077 // conversion to a qualified 'Class' type.
4078 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4079 return ImplicitConversionSequence::Worse;
4080 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4081 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004082
Douglas Gregor058d3de2011-01-31 18:51:41 +00004083 // -- "conversion of C* to B* is better than conversion of C* to A*,"
Alex Lorenza9832132017-04-06 13:06:34 +00004084 if (S.Context.hasSameType(FromType1, FromType2) &&
Douglas Gregor058d3de2011-01-31 18:51:41 +00004085 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
Alex Lorenza9832132017-04-06 13:06:34 +00004086 (ToAssignLeft != ToAssignRight)) {
4087 if (FromPtr1->isSpecialized()) {
4088 // "conversion of B<A> * to B * is better than conversion of B * to
4089 // C *.
4090 bool IsFirstSame =
4091 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4092 bool IsSecondSame =
4093 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4094 if (IsFirstSame) {
4095 if (!IsSecondSame)
4096 return ImplicitConversionSequence::Better;
4097 } else if (IsSecondSame)
4098 return ImplicitConversionSequence::Worse;
4099 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004100 return ToAssignLeft? ImplicitConversionSequence::Worse
4101 : ImplicitConversionSequence::Better;
Alex Lorenza9832132017-04-06 13:06:34 +00004102 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004103
4104 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4105 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4106 (FromAssignLeft != FromAssignRight))
4107 return FromAssignLeft? ImplicitConversionSequence::Better
4108 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004109 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004110 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004111
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004112 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004113 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4114 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4115 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004116 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004117 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004118 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004119 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004120 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004121 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004122 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004123 ToType2->getAs<MemberPointerType>();
4124 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4125 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4126 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4127 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4128 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4129 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4130 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4131 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004132 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004133 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004134 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004135 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004136 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004137 return ImplicitConversionSequence::Better;
4138 }
4139 // conversion of B::* to C::* is better than conversion of A::* to C::*
4140 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004141 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004142 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004143 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004144 return ImplicitConversionSequence::Worse;
4145 }
4146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004147
Douglas Gregor5ab11652010-04-17 22:01:05 +00004148 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004149 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004150 // -- binding of an expression of type C to a reference of type
4151 // B& is better than binding an expression of type C to a
4152 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004153 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4154 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004155 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004156 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004157 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004158 return ImplicitConversionSequence::Worse;
4159 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004160
Douglas Gregor2fe98832008-11-03 19:09:14 +00004161 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004162 // -- binding of an expression of type B to a reference of type
4163 // A& is better than binding an expression of type C to a
4164 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004165 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4166 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004167 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004168 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004169 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004170 return ImplicitConversionSequence::Worse;
4171 }
4172 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004173
Douglas Gregor5c407d92008-10-23 00:40:37 +00004174 return ImplicitConversionSequence::Indistinguishable;
4175}
4176
Douglas Gregor45bb4832013-03-26 23:36:30 +00004177/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4178/// C++ class.
4179static bool isTypeValid(QualType T) {
4180 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4181 return !Record->isInvalidDecl();
4182
4183 return true;
4184}
4185
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004186/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4187/// determine whether they are reference-related,
4188/// reference-compatible, reference-compatible with added
4189/// qualification, or incompatible, for use in C++ initialization by
4190/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4191/// type, and the first type (T1) is the pointee type of the reference
4192/// type being initialized.
4193Sema::ReferenceCompareResult
4194Sema::CompareReferenceRelationship(SourceLocation Loc,
4195 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004196 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004197 bool &ObjCConversion,
4198 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004199 assert(!OrigT1->isReferenceType() &&
4200 "T1 must be the pointee type of the reference type");
4201 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4202
4203 QualType T1 = Context.getCanonicalType(OrigT1);
4204 QualType T2 = Context.getCanonicalType(OrigT2);
4205 Qualifiers T1Quals, T2Quals;
4206 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4207 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4208
4209 // C++ [dcl.init.ref]p4:
4210 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4211 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4212 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004213 DerivedToBase = false;
4214 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004215 ObjCLifetimeConversion = false;
Richard Smith1be59c52016-10-22 01:32:19 +00004216 QualType ConvertedT2;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004217 if (UnqualT1 == UnqualT2) {
4218 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004219 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004220 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004221 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004222 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004223 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4224 UnqualT2->isObjCObjectOrInterfaceType() &&
4225 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4226 ObjCConversion = true;
Richard Smith1be59c52016-10-22 01:32:19 +00004227 else if (UnqualT2->isFunctionType() &&
4228 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4229 // C++1z [dcl.init.ref]p4:
4230 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4231 // function" and T1 is "function"
4232 //
4233 // We extend this to also apply to 'noreturn', so allow any function
4234 // conversion between function types.
4235 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004236 else
4237 return Ref_Incompatible;
4238
4239 // At this point, we know that T1 and T2 are reference-related (at
4240 // least).
4241
4242 // If the type is an array type, promote the element qualifiers to the type
4243 // for comparison.
4244 if (isa<ArrayType>(T1) && T1Quals)
4245 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4246 if (isa<ArrayType>(T2) && T2Quals)
4247 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4248
4249 // C++ [dcl.init.ref]p4:
4250 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4251 // reference-related to T2 and cv1 is the same cv-qualification
4252 // as, or greater cv-qualification than, cv2. For purposes of
4253 // overload resolution, cases for which cv1 is greater
4254 // cv-qualification than cv2 are identified as
4255 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004256 //
4257 // Note that we also require equivalence of Objective-C GC and address-space
4258 // qualifiers when performing these computations, so that e.g., an int in
4259 // address space 1 is not reference-compatible with an int in address
4260 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004261 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4262 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004263 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4264 ObjCLifetimeConversion = true;
4265
John McCall31168b02011-06-15 23:02:42 +00004266 T1Quals.removeObjCLifetime();
4267 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004268 }
4269
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004270 // MS compiler ignores __unaligned qualifier for references; do the same.
4271 T1Quals.removeUnaligned();
4272 T2Quals.removeUnaligned();
4273
Richard Smithce766292016-10-21 23:01:55 +00004274 if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004275 return Ref_Compatible;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004276 else
4277 return Ref_Related;
4278}
4279
George Burgess IVd5c7e7c2017-01-14 05:19:34 +00004280/// \brief Look for a user-defined conversion to a value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004281/// with DeclType. Return true if something definite is found.
4282static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004283FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4284 QualType DeclType, SourceLocation DeclLoc,
4285 Expr *Init, QualType T2, bool AllowRvalues,
4286 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004287 assert(T2->isRecordType() && "Can only find conversions of record types.");
4288 CXXRecordDecl *T2RecordDecl
4289 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4290
Richard Smith100b24a2014-04-17 01:52:14 +00004291 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004292 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4293 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004294 NamedDecl *D = *I;
4295 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4296 if (isa<UsingShadowDecl>(D))
4297 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4298
4299 FunctionTemplateDecl *ConvTemplate
4300 = dyn_cast<FunctionTemplateDecl>(D);
4301 CXXConversionDecl *Conv;
4302 if (ConvTemplate)
4303 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4304 else
4305 Conv = cast<CXXConversionDecl>(D);
4306
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004308 // explicit conversions, skip it.
4309 if (!AllowExplicit && Conv->isExplicit())
4310 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004311
Douglas Gregor836a7e82010-08-11 02:15:33 +00004312 if (AllowRvalues) {
4313 bool DerivedToBase = false;
4314 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004315 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004316
4317 // If we are initializing an rvalue reference, don't permit conversion
4318 // functions that return lvalues.
4319 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4320 const ReferenceType *RefType
4321 = Conv->getConversionType()->getAs<LValueReferenceType>();
4322 if (RefType && !RefType->getPointeeType()->isFunctionType())
4323 continue;
4324 }
4325
Douglas Gregor836a7e82010-08-11 02:15:33 +00004326 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004327 S.CompareReferenceRelationship(
4328 DeclLoc,
4329 Conv->getConversionType().getNonReferenceType()
4330 .getUnqualifiedType(),
4331 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004332 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004333 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004334 continue;
4335 } else {
4336 // If the conversion function doesn't return a reference type,
4337 // it can't be considered for this conversion. An rvalue reference
4338 // is only acceptable if its referencee is a function type.
4339
4340 const ReferenceType *RefType =
4341 Conv->getConversionType()->getAs<ReferenceType>();
4342 if (!RefType ||
4343 (!RefType->isLValueReferenceType() &&
4344 !RefType->getPointeeType()->isFunctionType()))
4345 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004346 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004347
Douglas Gregor836a7e82010-08-11 02:15:33 +00004348 if (ConvTemplate)
4349 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004350 Init, DeclType, CandidateSet,
4351 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004352 else
4353 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004354 DeclType, CandidateSet,
4355 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004356 }
4357
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004358 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4359
Sebastian Redld92badf2010-06-30 18:13:39 +00004360 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004361 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004362 case OR_Success:
4363 // C++ [over.ics.ref]p1:
4364 //
4365 // [...] If the parameter binds directly to the result of
4366 // applying a conversion function to the argument
4367 // expression, the implicit conversion sequence is a
4368 // user-defined conversion sequence (13.3.3.1.2), with the
4369 // second standard conversion sequence either an identity
4370 // conversion or, if the conversion function returns an
4371 // entity of a type that is a derived class of the parameter
4372 // type, a derived-to-base Conversion.
4373 if (!Best->FinalConversion.DirectBinding)
4374 return false;
4375
4376 ICS.setUserDefined();
4377 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4378 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004379 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004380 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004381 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004382 ICS.UserDefined.EllipsisConversion = false;
4383 assert(ICS.UserDefined.After.ReferenceBinding &&
4384 ICS.UserDefined.After.DirectBinding &&
4385 "Expected a direct reference binding!");
4386 return true;
4387
4388 case OR_Ambiguous:
4389 ICS.setAmbiguous();
4390 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4391 Cand != CandidateSet.end(); ++Cand)
4392 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004393 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004394 return true;
4395
4396 case OR_No_Viable_Function:
4397 case OR_Deleted:
4398 // There was no suitable conversion, or we found a deleted
4399 // conversion; continue with other checks.
4400 return false;
4401 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402
David Blaikie8a40f702012-01-17 06:56:22 +00004403 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004404}
4405
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004406/// \brief Compute an implicit conversion sequence for reference
4407/// initialization.
4408static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004409TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004410 SourceLocation DeclLoc,
4411 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004412 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004413 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4414
4415 // Most paths end in a failed conversion.
4416 ImplicitConversionSequence ICS;
4417 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4418
4419 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4420 QualType T2 = Init->getType();
4421
4422 // If the initializer is the address of an overloaded function, try
4423 // to resolve the overloaded function. If all goes well, T2 is the
4424 // type of the resulting function.
4425 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4426 DeclAccessPair Found;
4427 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4428 false, Found))
4429 T2 = Fn->getType();
4430 }
4431
4432 // Compute some basic properties of the types and the initializer.
4433 bool isRValRef = DeclType->isRValueReferenceType();
4434 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004435 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004436 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004437 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004438 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004439 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004440 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004441
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004442
Sebastian Redld92badf2010-06-30 18:13:39 +00004443 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004444 // A reference to type "cv1 T1" is initialized by an expression
4445 // of type "cv2 T2" as follows:
4446
Sebastian Redld92badf2010-06-30 18:13:39 +00004447 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004448 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004449 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4450 // reference-compatible with "cv2 T2," or
4451 //
4452 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
Richard Smithce766292016-10-21 23:01:55 +00004453 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004454 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004455 // When a parameter of reference type binds directly (8.5.3)
4456 // to an argument expression, the implicit conversion sequence
4457 // is the identity conversion, unless the argument expression
4458 // has a type that is a derived class of the parameter type,
4459 // in which case the implicit conversion sequence is a
4460 // derived-to-base Conversion (13.3.3.1).
4461 ICS.setStandard();
4462 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004463 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4464 : ObjCConversion? ICK_Compatible_Conversion
4465 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004466 ICS.Standard.Third = ICK_Identity;
4467 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4468 ICS.Standard.setToType(0, T2);
4469 ICS.Standard.setToType(1, T1);
4470 ICS.Standard.setToType(2, T1);
4471 ICS.Standard.ReferenceBinding = true;
4472 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004473 ICS.Standard.IsLvalueReference = !isRValRef;
4474 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4475 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004476 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004477 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004478 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004479 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004480
Sebastian Redld92badf2010-06-30 18:13:39 +00004481 // Nothing more to do: the inaccessibility/ambiguity check for
4482 // derived-to-base conversions is suppressed when we're
4483 // computing the implicit conversion sequence (C++
4484 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004485 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004486 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004487
Sebastian Redld92badf2010-06-30 18:13:39 +00004488 // -- has a class type (i.e., T2 is a class type), where T1 is
4489 // not reference-related to T2, and can be implicitly
4490 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4491 // is reference-compatible with "cv3 T3" 92) (this
4492 // conversion is selected by enumerating the applicable
4493 // conversion functions (13.3.1.6) and choosing the best
4494 // one through overload resolution (13.3)),
4495 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004496 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004497 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004498 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4499 Init, T2, /*AllowRvalues=*/false,
4500 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004501 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004502 }
4503 }
4504
Sebastian Redld92badf2010-06-30 18:13:39 +00004505 // -- Otherwise, the reference shall be an lvalue reference to a
4506 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004507 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004508 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004509 return ICS;
4510
Douglas Gregorf143cd52011-01-24 16:14:37 +00004511 // -- If the initializer expression
4512 //
4513 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004514 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Richard Smithce766292016-10-21 23:01:55 +00004515 if (RefRelationship == Sema::Ref_Compatible &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004516 (InitCategory.isXValue() ||
Richard Smithce766292016-10-21 23:01:55 +00004517 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4518 (InitCategory.isLValue() && T2->isFunctionType()))) {
Douglas Gregorf143cd52011-01-24 16:14:37 +00004519 ICS.setStandard();
4520 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004522 : ObjCConversion? ICK_Compatible_Conversion
4523 : ICK_Identity;
4524 ICS.Standard.Third = ICK_Identity;
4525 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4526 ICS.Standard.setToType(0, T2);
4527 ICS.Standard.setToType(1, T1);
4528 ICS.Standard.setToType(2, T1);
4529 ICS.Standard.ReferenceBinding = true;
4530 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4531 // binding unless we're binding to a class prvalue.
4532 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4533 // allow the use of rvalue references in C++98/03 for the benefit of
4534 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004535 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004536 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004537 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004538 ICS.Standard.IsLvalueReference = !isRValRef;
4539 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004540 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004541 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004542 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004543 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004544 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004547
Douglas Gregorf143cd52011-01-24 16:14:37 +00004548 // -- has a class type (i.e., T2 is a class type), where T1 is not
4549 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004550 // an xvalue, class prvalue, or function lvalue of type
4551 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004552 // "cv3 T3",
4553 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004555 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004556 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004557 // class subobject).
4558 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004559 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004560 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4561 Init, T2, /*AllowRvalues=*/true,
4562 AllowExplicit)) {
4563 // In the second case, if the reference is an rvalue reference
4564 // and the second standard conversion sequence of the
4565 // user-defined conversion sequence includes an lvalue-to-rvalue
4566 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004567 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004568 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4569 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4570
Douglas Gregor95273c32011-01-21 16:36:05 +00004571 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004572 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004573
Richard Smith19172c42014-07-14 02:28:44 +00004574 // A temporary of function type cannot be created; don't even try.
4575 if (T1->isFunctionType())
4576 return ICS;
4577
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004578 // -- Otherwise, a temporary of type "cv1 T1" is created and
4579 // initialized from the initializer expression using the
4580 // rules for a non-reference copy initialization (8.5). The
4581 // reference is then bound to the temporary. If T1 is
4582 // reference-related to T2, cv1 must be the same
4583 // cv-qualification as, or greater cv-qualification than,
4584 // cv2; otherwise, the program is ill-formed.
4585 if (RefRelationship == Sema::Ref_Related) {
4586 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4587 // we would be reference-compatible or reference-compatible with
4588 // added qualification. But that wasn't the case, so the reference
4589 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004590 //
4591 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004592 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004593 Qualifiers T1Quals = T1.getQualifiers();
4594 Qualifiers T2Quals = T2.getQualifiers();
4595 T1Quals.removeObjCGCAttr();
4596 T1Quals.removeObjCLifetime();
4597 T2Quals.removeObjCGCAttr();
4598 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004599 // MS compiler ignores __unaligned qualifier for references; do the same.
4600 T1Quals.removeUnaligned();
4601 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004602 if (!T1Quals.compatiblyIncludes(T2Quals))
4603 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004604 }
4605
4606 // If at least one of the types is a class type, the types are not
4607 // related, and we aren't allowed any user conversions, the
4608 // reference binding fails. This case is important for breaking
4609 // recursion, since TryImplicitConversion below will attempt to
4610 // create a temporary through the use of a copy constructor.
4611 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4612 (T1->isRecordType() || T2->isRecordType()))
4613 return ICS;
4614
Douglas Gregorcba72b12011-01-21 05:18:22 +00004615 // If T1 is reference-related to T2 and the reference is an rvalue
4616 // reference, the initializer expression shall not be an lvalue.
4617 if (RefRelationship >= Sema::Ref_Related &&
4618 isRValRef && Init->Classify(S.Context).isLValue())
4619 return ICS;
4620
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004621 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004622 // When a parameter of reference type is not bound directly to
4623 // an argument expression, the conversion sequence is the one
4624 // required to convert the argument expression to the
4625 // underlying type of the reference according to
4626 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4627 // to copy-initializing a temporary of the underlying type with
4628 // the argument expression. Any difference in top-level
4629 // cv-qualification is subsumed by the initialization itself
4630 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004631 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4632 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004633 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004634 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004635 /*AllowObjCWritebackConversion=*/false,
4636 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004637
4638 // Of course, that's still a reference binding.
4639 if (ICS.isStandard()) {
4640 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004641 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004642 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004643 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004644 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004645 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004646 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004647 const ReferenceType *LValRefType =
4648 ICS.UserDefined.ConversionFunction->getReturnType()
4649 ->getAs<LValueReferenceType>();
4650
4651 // C++ [over.ics.ref]p3:
4652 // Except for an implicit object parameter, for which see 13.3.1, a
4653 // standard conversion sequence cannot be formed if it requires [...]
4654 // binding an rvalue reference to an lvalue other than a function
4655 // lvalue.
4656 // Note that the function case is not possible here.
4657 if (DeclType->isRValueReferenceType() && LValRefType) {
4658 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4659 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4660 // reference to an rvalue!
4661 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4662 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004663 }
Richard Smith19172c42014-07-14 02:28:44 +00004664
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004665 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004666 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004667 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4668 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004669 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4670 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004671 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004672
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004673 return ICS;
4674}
4675
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004676static ImplicitConversionSequence
4677TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4678 bool SuppressUserConversions,
4679 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004680 bool AllowObjCWritebackConversion,
4681 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004682
4683/// TryListConversion - Try to copy-initialize a value of type ToType from the
4684/// initializer list From.
4685static ImplicitConversionSequence
4686TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4687 bool SuppressUserConversions,
4688 bool InOverloadResolution,
4689 bool AllowObjCWritebackConversion) {
4690 // C++11 [over.ics.list]p1:
4691 // When an argument is an initializer list, it is not an expression and
4692 // special rules apply for converting it to a parameter type.
4693
4694 ImplicitConversionSequence Result;
4695 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4696
Sebastian Redl09edce02012-01-23 22:09:39 +00004697 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004698 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004699 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004700 return Result;
4701
Larisse Voufo19d08672015-01-27 18:47:05 +00004702 // Per DR1467:
4703 // If the parameter type is a class X and the initializer list has a single
4704 // element of type cv U, where U is X or a class derived from X, the
4705 // implicit conversion sequence is the one required to convert the element
4706 // to the parameter type.
4707 //
4708 // Otherwise, if the parameter type is a character array [... ]
4709 // and the initializer list has a single element that is an
4710 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4711 // implicit conversion sequence is the identity conversion.
4712 if (From->getNumInits() == 1) {
4713 if (ToType->isRecordType()) {
4714 QualType InitType = From->getInit(0)->getType();
4715 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004716 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004717 return TryCopyInitialization(S, From->getInit(0), ToType,
4718 SuppressUserConversions,
4719 InOverloadResolution,
4720 AllowObjCWritebackConversion);
4721 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004722 // FIXME: Check the other conditions here: array of character type,
4723 // initializer is a string literal.
4724 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004725 InitializedEntity Entity =
4726 InitializedEntity::InitializeParameter(S.Context, ToType,
4727 /*Consumed=*/false);
4728 if (S.CanPerformCopyInitialization(Entity, From)) {
4729 Result.setStandard();
4730 Result.Standard.setAsIdentityConversion();
4731 Result.Standard.setFromType(ToType);
4732 Result.Standard.setAllToTypes(ToType);
4733 return Result;
4734 }
4735 }
4736 }
4737
4738 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004739 // C++11 [over.ics.list]p2:
4740 // If the parameter type is std::initializer_list<X> or "array of X" and
4741 // all the elements can be implicitly converted to X, the implicit
4742 // conversion sequence is the worst conversion necessary to convert an
4743 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004744 //
4745 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004746 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004747 // list has exactly N elements or if it has fewer than N elements and X is
4748 // default-constructible, and if all the elements of the initializer list
4749 // can be implicitly converted to X, the implicit conversion sequence is
4750 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004751 //
4752 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004753 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004754 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004755 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004756 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004757 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004758 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004759 if (!X.isNull()) {
4760 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4761 Expr *Init = From->getInit(i);
4762 ImplicitConversionSequence ICS =
4763 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4764 InOverloadResolution,
4765 AllowObjCWritebackConversion);
4766 // If a single element isn't convertible, fail.
4767 if (ICS.isBad()) {
4768 Result = ICS;
4769 break;
4770 }
4771 // Otherwise, look for the worst conversion.
4772 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004773 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4774 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004775 ImplicitConversionSequence::Worse)
4776 Result = ICS;
4777 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004778
4779 // For an empty list, we won't have computed any conversion sequence.
4780 // Introduce the identity conversion sequence.
4781 if (From->getNumInits() == 0) {
4782 Result.setStandard();
4783 Result.Standard.setAsIdentityConversion();
4784 Result.Standard.setFromType(ToType);
4785 Result.Standard.setAllToTypes(ToType);
4786 }
4787
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004788 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004789 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004790 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004791
Larisse Voufo19d08672015-01-27 18:47:05 +00004792 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004793 // C++11 [over.ics.list]p3:
4794 // Otherwise, if the parameter is a non-aggregate class X and overload
4795 // resolution chooses a single best constructor [...] the implicit
4796 // conversion sequence is a user-defined conversion sequence. If multiple
4797 // constructors are viable but none is better than the others, the
4798 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004799 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4800 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004801 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4802 /*AllowExplicit=*/false,
4803 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004804 AllowObjCWritebackConversion,
4805 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004806 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004807
Larisse Voufo19d08672015-01-27 18:47:05 +00004808 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004809 // C++11 [over.ics.list]p4:
4810 // Otherwise, if the parameter has an aggregate type which can be
4811 // initialized from the initializer list [...] the implicit conversion
4812 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004813 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004814 // Type is an aggregate, argument is an init list. At this point it comes
4815 // down to checking whether the initialization works.
4816 // FIXME: Find out whether this parameter is consumed or not.
Richard Smithb8c0f552016-12-09 18:49:13 +00004817 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4818 // need to call into the initialization code here; overload resolution
4819 // should not be doing that.
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004820 InitializedEntity Entity =
4821 InitializedEntity::InitializeParameter(S.Context, ToType,
4822 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004823 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004824 Result.setUserDefined();
4825 Result.UserDefined.Before.setAsIdentityConversion();
4826 // Initializer lists don't have a type.
4827 Result.UserDefined.Before.setFromType(QualType());
4828 Result.UserDefined.Before.setAllToTypes(QualType());
4829
4830 Result.UserDefined.After.setAsIdentityConversion();
4831 Result.UserDefined.After.setFromType(ToType);
4832 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004833 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004834 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004835 return Result;
4836 }
4837
Larisse Voufo19d08672015-01-27 18:47:05 +00004838 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004839 // C++11 [over.ics.list]p5:
4840 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004841 if (ToType->isReferenceType()) {
4842 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4843 // mention initializer lists in any way. So we go by what list-
4844 // initialization would do and try to extrapolate from that.
4845
4846 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4847
4848 // If the initializer list has a single element that is reference-related
4849 // to the parameter type, we initialize the reference from that.
4850 if (From->getNumInits() == 1) {
4851 Expr *Init = From->getInit(0);
4852
4853 QualType T2 = Init->getType();
4854
4855 // If the initializer is the address of an overloaded function, try
4856 // to resolve the overloaded function. If all goes well, T2 is the
4857 // type of the resulting function.
4858 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4859 DeclAccessPair Found;
4860 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4861 Init, ToType, false, Found))
4862 T2 = Fn->getType();
4863 }
4864
4865 // Compute some basic properties of the types and the initializer.
4866 bool dummy1 = false;
4867 bool dummy2 = false;
4868 bool dummy3 = false;
4869 Sema::ReferenceCompareResult RefRelationship
4870 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4871 dummy2, dummy3);
4872
Richard Smith4d2bbd72013-09-06 01:22:42 +00004873 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004874 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4875 SuppressUserConversions,
4876 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004877 }
Sebastian Redldf888642011-12-03 14:54:30 +00004878 }
4879
4880 // Otherwise, we bind the reference to a temporary created from the
4881 // initializer list.
4882 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4883 InOverloadResolution,
4884 AllowObjCWritebackConversion);
4885 if (Result.isFailure())
4886 return Result;
4887 assert(!Result.isEllipsis() &&
4888 "Sub-initialization cannot result in ellipsis conversion.");
4889
4890 // Can we even bind to a temporary?
4891 if (ToType->isRValueReferenceType() ||
4892 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4893 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4894 Result.UserDefined.After;
4895 SCS.ReferenceBinding = true;
4896 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4897 SCS.BindsToRvalue = true;
4898 SCS.BindsToFunctionLvalue = false;
4899 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4900 SCS.ObjCLifetimeConversionBinding = false;
4901 } else
4902 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4903 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004904 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004905 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004906
Larisse Voufo19d08672015-01-27 18:47:05 +00004907 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004908 // C++11 [over.ics.list]p6:
4909 // Otherwise, if the parameter type is not a class:
4910 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004911 // - if the initializer list has one element that is not itself an
4912 // initializer list, the implicit conversion sequence is the one
4913 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004914 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004915 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004916 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4917 SuppressUserConversions,
4918 InOverloadResolution,
4919 AllowObjCWritebackConversion);
4920 // - if the initializer list has no elements, the implicit conversion
4921 // sequence is the identity conversion.
4922 else if (NumInits == 0) {
4923 Result.setStandard();
4924 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004925 Result.Standard.setFromType(ToType);
4926 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004927 }
4928 return Result;
4929 }
4930
Larisse Voufo19d08672015-01-27 18:47:05 +00004931 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004932 // C++11 [over.ics.list]p7:
4933 // In all cases other than those enumerated above, no conversion is possible
4934 return Result;
4935}
4936
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004937/// TryCopyInitialization - Try to copy-initialize a value of type
4938/// ToType from the expression From. Return the implicit conversion
4939/// sequence required to pass this argument, which may be a bad
4940/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004941/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004942/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004943static ImplicitConversionSequence
4944TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004945 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004946 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004947 bool AllowObjCWritebackConversion,
4948 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004949 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4950 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4951 InOverloadResolution,AllowObjCWritebackConversion);
4952
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004953 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004954 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004955 /*FIXME:*/From->getLocStart(),
4956 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004957 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004958
John McCall5c32be02010-08-24 20:38:10 +00004959 return TryImplicitConversion(S, From, ToType,
4960 SuppressUserConversions,
4961 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004962 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004963 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004964 AllowObjCWritebackConversion,
4965 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004966}
4967
Anna Zaks1b068122011-07-28 19:46:48 +00004968static bool TryCopyInitialization(const CanQualType FromQTy,
4969 const CanQualType ToQTy,
4970 Sema &S,
4971 SourceLocation Loc,
4972 ExprValueKind FromVK) {
4973 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4974 ImplicitConversionSequence ICS =
4975 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4976
4977 return !ICS.isBad();
4978}
4979
Douglas Gregor436424c2008-11-18 23:14:02 +00004980/// TryObjectArgumentInitialization - Try to initialize the object
4981/// parameter of the given member function (@c Method) from the
4982/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004983static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004984TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004985 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004986 CXXMethodDecl *Method,
4987 CXXRecordDecl *ActingContext) {
4988 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004989 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4990 // const volatile object.
4991 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4992 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004993 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004994
4995 // Set up the conversion sequence as a "bad" conversion, to allow us
4996 // to exit early.
4997 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004998
4999 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00005000 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005001 FromType = PT->getPointeeType();
5002
Douglas Gregor02824322011-01-26 19:30:28 +00005003 // When we had a pointer, it's implicitly dereferenced, so we
5004 // better have an lvalue.
5005 assert(FromClassification.isLValue());
5006 }
5007
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005008 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00005009
Douglas Gregor02824322011-01-26 19:30:28 +00005010 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00005012 // parameter is
5013 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005014 // - "lvalue reference to cv X" for functions declared without a
5015 // ref-qualifier or with the & ref-qualifier
5016 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00005017 // ref-qualifier
5018 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005019 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00005020 // cv-qualification on the member function declaration.
5021 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005022 // However, when finding an implicit conversion sequence for the argument, we
Richard Smith122f88d2016-12-06 23:52:28 +00005023 // are not allowed to perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00005024 // (C++ [over.match.funcs]p5). We perform a simplified version of
5025 // reference binding here, that allows class rvalues to bind to
5026 // non-constant references.
5027
Douglas Gregor02824322011-01-26 19:30:28 +00005028 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00005029 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005030 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005031 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00005032 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00005033 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00005034 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005035 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005036 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005037
5038 // Check that we have either the same type or a derived type. It
5039 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00005040 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00005041 ImplicitConversionKind SecondKind;
5042 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5043 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00005044 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00005045 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00005046 else {
John McCall65eb8792010-02-25 01:37:24 +00005047 ICS.setBad(BadConversionSequence::unrelated_class,
5048 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005049 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00005050 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005051
Douglas Gregor02824322011-01-26 19:30:28 +00005052 // Check the ref-qualifier.
5053 switch (Method->getRefQualifier()) {
5054 case RQ_None:
5055 // Do nothing; we don't care about lvalueness or rvalueness.
5056 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005057
Douglas Gregor02824322011-01-26 19:30:28 +00005058 case RQ_LValue:
5059 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5060 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005061 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005062 ImplicitParamType);
5063 return ICS;
5064 }
5065 break;
5066
5067 case RQ_RValue:
5068 if (!FromClassification.isRValue()) {
5069 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005070 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00005071 ImplicitParamType);
5072 return ICS;
5073 }
5074 break;
5075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076
Douglas Gregor436424c2008-11-18 23:14:02 +00005077 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00005078 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00005079 ICS.Standard.setAsIdentityConversion();
5080 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00005081 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005082 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00005083 ICS.Standard.ReferenceBinding = true;
5084 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005085 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00005086 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00005087 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5088 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5089 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00005090 return ICS;
5091}
5092
5093/// PerformObjectArgumentInitialization - Perform initialization of
5094/// the implicit object parameter for the given Method with the given
5095/// expression.
John Wiegley01296292011-04-08 18:41:53 +00005096ExprResult
5097Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005098 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00005099 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005100 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005101 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005102 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005103 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005104
Douglas Gregor02824322011-01-26 19:30:28 +00005105 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005106 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005107 FromRecordType = PT->getPointeeType();
5108 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005109 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005110 } else {
5111 FromRecordType = From->getType();
5112 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005113 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005114 }
5115
John McCall6e9f8f62009-12-03 04:06:58 +00005116 // Note that we always use the true parent context when performing
5117 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005118 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005119 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5120 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005121 if (ICS.isBad()) {
5122 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5123 Qualifiers FromQs = FromRecordType.getQualifiers();
5124 Qualifiers ToQs = DestType.getQualifiers();
5125 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5126 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005127 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005128 diag::err_member_function_call_bad_cvr)
5129 << Method->getDeclName() << FromRecordType << (CVR - 1)
5130 << From->getSourceRange();
5131 Diag(Method->getLocation(), diag::note_previous_decl)
5132 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005133 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005134 }
5135 }
5136
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005137 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005138 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005139 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005140 }
Mike Stump11289f42009-09-09 15:08:12 +00005141
John Wiegley01296292011-04-08 18:41:53 +00005142 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5143 ExprResult FromRes =
5144 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5145 if (FromRes.isInvalid())
5146 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005147 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005148 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005149
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005150 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005151 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005152 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005153 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005154}
5155
Douglas Gregor5fb53972009-01-14 15:45:31 +00005156/// TryContextuallyConvertToBool - Attempt to contextually convert the
5157/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005158static ImplicitConversionSequence
5159TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005160 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005161 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005162 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005163 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005164 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005165 /*AllowObjCWritebackConversion=*/false,
5166 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005167}
5168
5169/// PerformContextuallyConvertToBool - Perform a contextual conversion
5170/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005171ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005172 if (checkPlaceholderForOverload(*this, From))
5173 return ExprError();
5174
John McCall5c32be02010-08-24 20:38:10 +00005175 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005176 if (!ICS.isBad())
5177 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005178
Fariborz Jahanian76197412009-11-18 18:26:29 +00005179 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005180 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005181 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005182 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005183 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005184}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005185
Richard Smithf8379a02012-01-18 23:55:52 +00005186/// Check that the specified conversion is permitted in a converted constant
5187/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5188/// is acceptable.
5189static bool CheckConvertedConstantConversions(Sema &S,
5190 StandardConversionSequence &SCS) {
5191 // Since we know that the target type is an integral or unscoped enumeration
5192 // type, most conversion kinds are impossible. All possible First and Third
5193 // conversions are fine.
5194 switch (SCS.Second) {
5195 case ICK_Identity:
Richard Smith3c4f8d22016-10-16 17:54:23 +00005196 case ICK_Function_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005197 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005198 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Egor Churaev89831422016-12-23 14:55:49 +00005199 case ICK_Zero_Queue_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005200 return true;
5201
5202 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005203 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005204 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5205 // conversion, so we allow it in a converted constant expression.
5206 //
5207 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5208 // a lot of popular code. We should at least add a warning for this
5209 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005210 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5211 SCS.getToType(2)->isBooleanType();
5212
Richard Smith410cc892014-11-26 03:26:53 +00005213 case ICK_Pointer_Conversion:
5214 case ICK_Pointer_Member:
5215 // C++1z: null pointer conversions and null member pointer conversions are
5216 // only permitted if the source type is std::nullptr_t.
5217 return SCS.getFromType()->isNullPtrType();
5218
5219 case ICK_Floating_Promotion:
5220 case ICK_Complex_Promotion:
5221 case ICK_Floating_Conversion:
5222 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005223 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005224 case ICK_Compatible_Conversion:
5225 case ICK_Derived_To_Base:
5226 case ICK_Vector_Conversion:
5227 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005228 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005229 case ICK_Block_Pointer_Conversion:
5230 case ICK_TransparentUnionConversion:
5231 case ICK_Writeback_Conversion:
5232 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005233 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005234 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005235 return false;
5236
5237 case ICK_Lvalue_To_Rvalue:
5238 case ICK_Array_To_Pointer:
5239 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005240 llvm_unreachable("found a first conversion kind in Second");
5241
Richard Smithf8379a02012-01-18 23:55:52 +00005242 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005243 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005244
5245 case ICK_Num_Conversion_Kinds:
5246 break;
5247 }
5248
5249 llvm_unreachable("unknown conversion kind");
5250}
5251
5252/// CheckConvertedConstantExpression - Check that the expression From is a
5253/// converted constant expression of type T, perform the conversion and produce
5254/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005255static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5256 QualType T, APValue &Value,
5257 Sema::CCEKind CCE,
5258 bool RequireInt) {
5259 assert(S.getLangOpts().CPlusPlus11 &&
5260 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005261
Richard Smith410cc892014-11-26 03:26:53 +00005262 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005263 return ExprError();
5264
Richard Smith410cc892014-11-26 03:26:53 +00005265 // C++1z [expr.const]p3:
5266 // A converted constant expression of type T is an expression,
5267 // implicitly converted to type T, where the converted
5268 // expression is a constant expression and the implicit conversion
5269 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005270 // C++1z [stmt.if]p2:
5271 // If the if statement is of the form if constexpr, the value of the
5272 // condition shall be a contextually converted constant expression of type
5273 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005274 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005275 CCE == Sema::CCEK_ConstexprIf
5276 ? TryContextuallyConvertToBool(S, From)
5277 : TryCopyInitialization(S, From, T,
5278 /*SuppressUserConversions=*/false,
5279 /*InOverloadResolution=*/false,
5280 /*AllowObjcWritebackConversion=*/false,
5281 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005282 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005283 switch (ICS.getKind()) {
5284 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005285 SCS = &ICS.Standard;
5286 break;
5287 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005288 // We are converting to a non-class type, so the Before sequence
5289 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005290 SCS = &ICS.UserDefined.After;
5291 break;
5292 case ImplicitConversionSequence::AmbiguousConversion:
5293 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005294 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5295 return S.Diag(From->getLocStart(),
5296 diag::err_typecheck_converted_constant_expression)
5297 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005298 return ExprError();
5299
5300 case ImplicitConversionSequence::EllipsisConversion:
5301 llvm_unreachable("ellipsis conversion in converted constant expression");
5302 }
5303
Richard Smith410cc892014-11-26 03:26:53 +00005304 // Check that we would only use permitted conversions.
5305 if (!CheckConvertedConstantConversions(S, *SCS)) {
5306 return S.Diag(From->getLocStart(),
5307 diag::err_typecheck_converted_constant_expression_disallowed)
5308 << From->getType() << From->getSourceRange() << T;
5309 }
5310 // [...] and where the reference binding (if any) binds directly.
5311 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5312 return S.Diag(From->getLocStart(),
5313 diag::err_typecheck_converted_constant_expression_indirect)
5314 << From->getType() << From->getSourceRange() << T;
5315 }
5316
5317 ExprResult Result =
5318 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005319 if (Result.isInvalid())
5320 return Result;
5321
5322 // Check for a narrowing implicit conversion.
5323 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005324 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005325 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005326 PreNarrowingType)) {
Richard Smith52e624f2016-12-21 21:42:57 +00005327 case NK_Dependent_Narrowing:
5328 // Implicit conversion to a narrower type, but the expression is
5329 // value-dependent so we can't tell whether it's actually narrowing.
Richard Smithf8379a02012-01-18 23:55:52 +00005330 case NK_Variable_Narrowing:
5331 // Implicit conversion to a narrower type, and the value is not a constant
5332 // expression. We'll diagnose this in a moment.
5333 case NK_Not_Narrowing:
5334 break;
5335
5336 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005337 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005338 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005339 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005340 break;
5341
5342 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005343 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005344 << CCE << /*Constant*/0 << From->getType() << T;
5345 break;
5346 }
5347
Richard Smith52e624f2016-12-21 21:42:57 +00005348 if (Result.get()->isValueDependent()) {
5349 Value = APValue();
5350 return Result;
5351 }
5352
Richard Smithf8379a02012-01-18 23:55:52 +00005353 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005354 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005355 Expr::EvalResult Eval;
5356 Eval.Diag = &Notes;
5357
Richard Smith410cc892014-11-26 03:26:53 +00005358 if ((T->isReferenceType()
5359 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5360 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5361 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005362 // The expression can't be folded, so we can't keep it at this position in
5363 // the AST.
5364 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005365 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005366 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005367
5368 if (Notes.empty()) {
5369 // It's a constant expression.
5370 return Result;
5371 }
Richard Smithf8379a02012-01-18 23:55:52 +00005372 }
5373
5374 // It's not a constant expression. Produce an appropriate diagnostic.
5375 if (Notes.size() == 1 &&
5376 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005377 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005378 else {
Richard Smith410cc892014-11-26 03:26:53 +00005379 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005380 << CCE << From->getSourceRange();
5381 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005382 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005383 }
Richard Smith410cc892014-11-26 03:26:53 +00005384 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005385}
5386
Richard Smith410cc892014-11-26 03:26:53 +00005387ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5388 APValue &Value, CCEKind CCE) {
5389 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5390}
5391
5392ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5393 llvm::APSInt &Value,
5394 CCEKind CCE) {
5395 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5396
5397 APValue V;
5398 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
Richard Smith01bfa682016-12-27 02:02:09 +00005399 if (!R.isInvalid() && !R.get()->isValueDependent())
Richard Smith410cc892014-11-26 03:26:53 +00005400 Value = V.getInt();
5401 return R;
5402}
5403
5404
John McCallfec112d2011-09-09 06:11:02 +00005405/// dropPointerConversions - If the given standard conversion sequence
5406/// involves any pointer conversions, remove them. This may change
5407/// the result type of the conversion sequence.
5408static void dropPointerConversion(StandardConversionSequence &SCS) {
5409 if (SCS.Second == ICK_Pointer_Conversion) {
5410 SCS.Second = ICK_Identity;
5411 SCS.Third = ICK_Identity;
5412 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5413 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005414}
John McCall5c32be02010-08-24 20:38:10 +00005415
John McCallfec112d2011-09-09 06:11:02 +00005416/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5417/// convert the expression From to an Objective-C pointer type.
5418static ImplicitConversionSequence
5419TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5420 // Do an implicit conversion to 'id'.
5421 QualType Ty = S.Context.getObjCIdType();
5422 ImplicitConversionSequence ICS
5423 = TryImplicitConversion(S, From, Ty,
5424 // FIXME: Are these flags correct?
5425 /*SuppressUserConversions=*/false,
5426 /*AllowExplicit=*/true,
5427 /*InOverloadResolution=*/false,
5428 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005429 /*AllowObjCWritebackConversion=*/false,
5430 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005431
5432 // Strip off any final conversions to 'id'.
5433 switch (ICS.getKind()) {
5434 case ImplicitConversionSequence::BadConversion:
5435 case ImplicitConversionSequence::AmbiguousConversion:
5436 case ImplicitConversionSequence::EllipsisConversion:
5437 break;
5438
5439 case ImplicitConversionSequence::UserDefinedConversion:
5440 dropPointerConversion(ICS.UserDefined.After);
5441 break;
5442
5443 case ImplicitConversionSequence::StandardConversion:
5444 dropPointerConversion(ICS.Standard);
5445 break;
5446 }
5447
5448 return ICS;
5449}
5450
5451/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5452/// conversion of the expression From to an Objective-C pointer type.
Richard Smithe15a3702016-10-06 23:12:58 +00005453/// Returns a valid but null ExprResult if no conversion sequence exists.
John McCallfec112d2011-09-09 06:11:02 +00005454ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005455 if (checkPlaceholderForOverload(*this, From))
5456 return ExprError();
5457
John McCall8b07ec22010-05-15 11:32:37 +00005458 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005459 ImplicitConversionSequence ICS =
5460 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005461 if (!ICS.isBad())
5462 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
Richard Smithe15a3702016-10-06 23:12:58 +00005463 return ExprResult();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005464}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005465
Richard Smith8dd34252012-02-04 07:07:42 +00005466/// Determine whether the provided type is an integral type, or an enumeration
5467/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005468bool Sema::ICEConvertDiagnoser::match(QualType T) {
5469 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5470 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005471}
5472
Larisse Voufo236bec22013-06-10 06:50:24 +00005473static ExprResult
5474diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5475 Sema::ContextualImplicitConverter &Converter,
5476 QualType T, UnresolvedSetImpl &ViableConversions) {
5477
5478 if (Converter.Suppress)
5479 return ExprError();
5480
5481 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5482 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5483 CXXConversionDecl *Conv =
5484 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5485 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5486 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5487 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005488 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005489}
5490
5491static bool
5492diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5493 Sema::ContextualImplicitConverter &Converter,
5494 QualType T, bool HadMultipleCandidates,
5495 UnresolvedSetImpl &ExplicitConversions) {
5496 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5497 DeclAccessPair Found = ExplicitConversions[0];
5498 CXXConversionDecl *Conversion =
5499 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5500
5501 // The user probably meant to invoke the given explicit
5502 // conversion; use it.
5503 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5504 std::string TypeStr;
5505 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5506
5507 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5508 << FixItHint::CreateInsertion(From->getLocStart(),
5509 "static_cast<" + TypeStr + ">(")
5510 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005511 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005512 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5513
5514 // If we aren't in a SFINAE context, build a call to the
5515 // explicit conversion function.
5516 if (SemaRef.isSFINAEContext())
5517 return true;
5518
Craig Topperc3ec1492014-05-26 06:22:03 +00005519 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005520 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5521 HadMultipleCandidates);
5522 if (Result.isInvalid())
5523 return true;
5524 // Record usage of conversion in an implicit cast.
5525 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005526 CK_UserDefinedConversion, Result.get(),
5527 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005528 }
5529 return false;
5530}
5531
5532static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5533 Sema::ContextualImplicitConverter &Converter,
5534 QualType T, bool HadMultipleCandidates,
5535 DeclAccessPair &Found) {
5536 CXXConversionDecl *Conversion =
5537 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005538 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005539
5540 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5541 if (!Converter.SuppressConversion) {
5542 if (SemaRef.isSFINAEContext())
5543 return true;
5544
5545 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5546 << From->getSourceRange();
5547 }
5548
5549 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5550 HadMultipleCandidates);
5551 if (Result.isInvalid())
5552 return true;
5553 // Record usage of conversion in an implicit cast.
5554 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005555 CK_UserDefinedConversion, Result.get(),
5556 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005557 return false;
5558}
5559
5560static ExprResult finishContextualImplicitConversion(
5561 Sema &SemaRef, SourceLocation Loc, Expr *From,
5562 Sema::ContextualImplicitConverter &Converter) {
5563 if (!Converter.match(From->getType()) && !Converter.Suppress)
5564 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5565 << From->getSourceRange();
5566
5567 return SemaRef.DefaultLvalueConversion(From);
5568}
5569
5570static void
5571collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5572 UnresolvedSetImpl &ViableConversions,
5573 OverloadCandidateSet &CandidateSet) {
5574 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5575 DeclAccessPair FoundDecl = ViableConversions[I];
5576 NamedDecl *D = FoundDecl.getDecl();
5577 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5578 if (isa<UsingShadowDecl>(D))
5579 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5580
5581 CXXConversionDecl *Conv;
5582 FunctionTemplateDecl *ConvTemplate;
5583 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5584 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5585 else
5586 Conv = cast<CXXConversionDecl>(D);
5587
5588 if (ConvTemplate)
5589 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005590 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5591 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005592 else
5593 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005594 ToType, CandidateSet,
5595 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005596 }
5597}
5598
Richard Smithccc11812013-05-21 19:05:48 +00005599/// \brief Attempt to convert the given expression to a type which is accepted
5600/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005601///
Richard Smithccc11812013-05-21 19:05:48 +00005602/// This routine will attempt to convert an expression of class type to a
5603/// type accepted by the specified converter. In C++11 and before, the class
5604/// must have a single non-explicit conversion function converting to a matching
5605/// type. In C++1y, there can be multiple such conversion functions, but only
5606/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005607///
Douglas Gregor4799d032010-06-30 00:20:43 +00005608/// \param Loc The source location of the construct that requires the
5609/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005610///
James Dennett18348b62012-06-22 08:52:37 +00005611/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005612///
Richard Smithccc11812013-05-21 19:05:48 +00005613/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005614///
Douglas Gregor4799d032010-06-30 00:20:43 +00005615/// \returns The expression, converted to an integral or enumeration type if
5616/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005617ExprResult Sema::PerformContextualImplicitConversion(
5618 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005619 // We can't perform any more checking for type-dependent expressions.
5620 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005621 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005622
Eli Friedman1da70392012-01-26 00:26:18 +00005623 // Process placeholders immediately.
5624 if (From->hasPlaceholderType()) {
5625 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005626 if (result.isInvalid())
5627 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005628 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005629 }
5630
Richard Smithccc11812013-05-21 19:05:48 +00005631 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005632 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005633 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005634 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005635
5636 // FIXME: Check for missing '()' if T is a function type?
5637
Richard Smithccc11812013-05-21 19:05:48 +00005638 // We can only perform contextual implicit conversions on objects of class
5639 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005640 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005641 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005642 if (!Converter.Suppress)
5643 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005644 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005646
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005647 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005648 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005649 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005650 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005651
5652 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005653 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005654
Craig Toppere14c0f82014-03-12 04:55:44 +00005655 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005656 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005657 }
Richard Smithccc11812013-05-21 19:05:48 +00005658 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005659
Richard Smithdb0ac552015-12-18 22:40:25 +00005660 if (Converter.Suppress ? !isCompleteType(Loc, T)
5661 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005662 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005663
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005664 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005665 UnresolvedSet<4>
5666 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005667 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005668 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005669 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670
Larisse Voufo236bec22013-06-10 06:50:24 +00005671 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005672 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005673
Larisse Voufo236bec22013-06-10 06:50:24 +00005674 // To check that there is only one target type, in C++1y:
5675 QualType ToType;
5676 bool HasUniqueTargetType = true;
5677
5678 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005679 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005680 NamedDecl *D = (*I)->getUnderlyingDecl();
5681 CXXConversionDecl *Conversion;
5682 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5683 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005684 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005685 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5686 else
5687 continue; // C++11 does not consider conversion operator templates(?).
5688 } else
5689 Conversion = cast<CXXConversionDecl>(D);
5690
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005691 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005692 "Conversion operator templates are considered potentially "
5693 "viable in C++1y");
5694
5695 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5696 if (Converter.match(CurToType) || ConvTemplate) {
5697
5698 if (Conversion->isExplicit()) {
5699 // FIXME: For C++1y, do we need this restriction?
5700 // cf. diagnoseNoViableConversion()
5701 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005702 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005703 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005704 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005705 if (ToType.isNull())
5706 ToType = CurToType.getUnqualifiedType();
5707 else if (HasUniqueTargetType &&
5708 (CurToType.getUnqualifiedType() != ToType))
5709 HasUniqueTargetType = false;
5710 }
5711 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005712 }
Richard Smith8dd34252012-02-04 07:07:42 +00005713 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005715
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005716 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005717 // C++1y [conv]p6:
5718 // ... An expression e of class type E appearing in such a context
5719 // is said to be contextually implicitly converted to a specified
5720 // type T and is well-formed if and only if e can be implicitly
5721 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005722 // for conversion functions whose return type is cv T or reference to
5723 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005724 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005725
Larisse Voufo236bec22013-06-10 06:50:24 +00005726 // If no unique T is found:
5727 if (ToType.isNull()) {
5728 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5729 HadMultipleCandidates,
5730 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005731 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005732 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005733 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005734
Larisse Voufo236bec22013-06-10 06:50:24 +00005735 // If more than one unique Ts are found:
5736 if (!HasUniqueTargetType)
5737 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5738 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005739
Larisse Voufo236bec22013-06-10 06:50:24 +00005740 // If one unique T is found:
5741 // First, build a candidate set from the previously recorded
5742 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005743 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005744 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5745 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005746
Larisse Voufo236bec22013-06-10 06:50:24 +00005747 // Then, perform overload resolution over the candidate set.
5748 OverloadCandidateSet::iterator Best;
5749 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5750 case OR_Success: {
5751 // Apply this conversion.
5752 DeclAccessPair Found =
5753 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5754 if (recordConversion(*this, Loc, From, Converter, T,
5755 HadMultipleCandidates, Found))
5756 return ExprError();
5757 break;
5758 }
5759 case OR_Ambiguous:
5760 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5761 ViableConversions);
5762 case OR_No_Viable_Function:
5763 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5764 HadMultipleCandidates,
5765 ExplicitConversions))
5766 return ExprError();
5767 // fall through 'OR_Deleted' case.
5768 case OR_Deleted:
5769 // We'll complain below about a non-integral condition type.
5770 break;
5771 }
5772 } else {
5773 switch (ViableConversions.size()) {
5774 case 0: {
5775 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5776 HadMultipleCandidates,
5777 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005778 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005779
Larisse Voufo236bec22013-06-10 06:50:24 +00005780 // We'll complain below about a non-integral condition type.
5781 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005782 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005783 case 1: {
5784 // Apply this conversion.
5785 DeclAccessPair Found = ViableConversions[0];
5786 if (recordConversion(*this, Loc, From, Converter, T,
5787 HadMultipleCandidates, Found))
5788 return ExprError();
5789 break;
5790 }
5791 default:
5792 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5793 ViableConversions);
5794 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005795 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005796
Larisse Voufo236bec22013-06-10 06:50:24 +00005797 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005798}
5799
Richard Smith100b24a2014-04-17 01:52:14 +00005800/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5801/// an acceptable non-member overloaded operator for a call whose
5802/// arguments have types T1 (and, if non-empty, T2). This routine
5803/// implements the check in C++ [over.match.oper]p3b2 concerning
5804/// enumeration types.
5805static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5806 FunctionDecl *Fn,
5807 ArrayRef<Expr *> Args) {
5808 QualType T1 = Args[0]->getType();
5809 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5810
5811 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5812 return true;
5813
5814 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5815 return true;
5816
5817 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5818 if (Proto->getNumParams() < 1)
5819 return false;
5820
5821 if (T1->isEnumeralType()) {
5822 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5823 if (Context.hasSameUnqualifiedType(T1, ArgType))
5824 return true;
5825 }
5826
5827 if (Proto->getNumParams() < 2)
5828 return false;
5829
5830 if (!T2.isNull() && T2->isEnumeralType()) {
5831 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5832 if (Context.hasSameUnqualifiedType(T2, ArgType))
5833 return true;
5834 }
5835
5836 return false;
5837}
5838
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005839/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005840/// candidate functions, using the given function call arguments. If
5841/// @p SuppressUserConversions, then don't allow user-defined
5842/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005843///
James Dennett2a4d13c2012-06-15 07:13:21 +00005844/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005845/// based on an incomplete set of function arguments. This feature is used by
5846/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005847void
5848Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005849 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005850 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005851 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005852 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005853 bool PartialOverloading,
Richard Smith6eedfe72017-01-09 08:01:21 +00005854 bool AllowExplicit,
5855 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005856 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005857 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005858 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005859 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005860 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005861
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005862 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005863 if (!isa<CXXConstructorDecl>(Method)) {
5864 // If we get here, it's because we're calling a member function
5865 // that is named without a member access expression (e.g.,
5866 // "this->f") that was either written explicitly or created
5867 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005868 // function, e.g., X::f(). We use an empty type for the implied
5869 // object argument (C++ [over.call.func]p3), and the acting context
5870 // is irrelevant.
Richard Smith6eedfe72017-01-09 08:01:21 +00005871 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00005872 Expr::Classification::makeSimpleLValue(), Args,
5873 CandidateSet, SuppressUserConversions,
5874 PartialOverloading, EarlyConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005875 return;
5876 }
5877 // We treat a constructor like a non-member function, since its object
5878 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005879 }
5880
Douglas Gregorff7028a2009-11-13 23:59:09 +00005881 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005882 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005883
Richard Smith100b24a2014-04-17 01:52:14 +00005884 // C++ [over.match.oper]p3:
5885 // if no operand has a class type, only those non-member functions in the
5886 // lookup set that have a first parameter of type T1 or "reference to
5887 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5888 // is a right operand) a second parameter of type T2 or "reference to
5889 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5890 // candidate functions.
5891 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5892 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5893 return;
5894
Richard Smith8b86f2d2013-11-04 01:48:18 +00005895 // C++11 [class.copy]p11: [DR1402]
5896 // A defaulted move constructor that is defined as deleted is ignored by
5897 // overload resolution.
5898 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5899 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5900 Constructor->isMoveConstructor())
5901 return;
5902
Douglas Gregor27381f32009-11-23 12:27:39 +00005903 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00005904 EnterExpressionEvaluationContext Unevaluated(
5905 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005906
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005907 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00005908 OverloadCandidate &Candidate =
5909 CandidateSet.addCandidate(Args.size(), EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00005910 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005911 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005912 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005913 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005914 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005915 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005916
John McCall578a1f82014-12-14 01:46:53 +00005917 if (Constructor) {
5918 // C++ [class.copy]p3:
5919 // A member function template is never instantiated to perform the copy
5920 // of a class object to an object of its class type.
5921 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005922 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005923 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005924 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5925 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005926 Candidate.Viable = false;
5927 Candidate.FailureKind = ovl_fail_illegal_constructor;
5928 return;
5929 }
Richard Smith836a3b42017-01-13 20:46:54 +00005930
5931 // C++ [over.match.funcs]p8: (proposed DR resolution)
5932 // A constructor inherited from class type C that has a first parameter
5933 // of type "reference to P" (including such a constructor instantiated
5934 // from a template) is excluded from the set of candidate functions when
5935 // constructing an object of type cv D if the argument list has exactly
5936 // one argument and D is reference-related to P and P is reference-related
5937 // to C.
5938 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
5939 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
5940 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
5941 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
5942 QualType C = Context.getRecordType(Constructor->getParent());
5943 QualType D = Context.getRecordType(Shadow->getParent());
5944 SourceLocation Loc = Args.front()->getExprLoc();
5945 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
5946 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
5947 Candidate.Viable = false;
5948 Candidate.FailureKind = ovl_fail_inhctor_slice;
5949 return;
5950 }
5951 }
John McCall578a1f82014-12-14 01:46:53 +00005952 }
5953
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005954 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005955
5956 // (C++ 13.3.2p2): A candidate function having fewer than m
5957 // parameters is viable only if it has an ellipsis in its parameter
5958 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005959 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005960 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005961 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005962 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005963 return;
5964 }
5965
5966 // (C++ 13.3.2p2): A candidate function having more than m parameters
5967 // is viable only if the (m+1)st parameter has a default argument
5968 // (8.3.6). For the purposes of overload resolution, the
5969 // parameter list is truncated on the right, so that there are
5970 // exactly m parameters.
5971 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005972 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005973 // Not enough arguments.
5974 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005975 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005976 return;
5977 }
5978
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005979 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005980 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005981 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005982 // Skip the check for callers that are implicit members, because in this
5983 // case we may not yet know what the member's target is; the target is
5984 // inferred for the member automatically, based on the bases and fields of
5985 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00005986 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005987 Candidate.Viable = false;
5988 Candidate.FailureKind = ovl_fail_bad_target;
5989 return;
5990 }
5991
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005992 // Determine the implicit conversion sequences for each of the
5993 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005994 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00005995 if (Candidate.Conversions[ArgIdx].isInitialized()) {
5996 // We already formed a conversion sequence for this parameter during
5997 // template argument deduction.
5998 } else if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005999 // (C++ 13.3.2p3): for F to be a viable function, there shall
6000 // exist for each argument an implicit conversion sequence
6001 // (13.3.3.1) that converts that argument to the corresponding
6002 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006003 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006004 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006005 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006006 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006007 /*InOverloadResolution=*/true,
6008 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006009 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00006010 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00006011 if (Candidate.Conversions[ArgIdx].isBad()) {
6012 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006013 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006014 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006015 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006016 } else {
6017 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6018 // argument for which there is no corresponding parameter is
6019 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006020 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006021 }
6022 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006023
6024 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6025 Candidate.Viable = false;
6026 Candidate.FailureKind = ovl_fail_enable_if;
6027 Candidate.DeductionFailure.Data = FailedAttr;
6028 return;
6029 }
Yaxun Liu5b746652016-12-18 05:18:55 +00006030
6031 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6032 Candidate.Viable = false;
6033 Candidate.FailureKind = ovl_fail_ext_disabled;
6034 return;
6035 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006036}
6037
Manman Rend2a3cd72016-04-07 19:30:20 +00006038ObjCMethodDecl *
6039Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6040 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6041 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00006042 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00006043
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006044 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6045 bool Match = true;
6046 ObjCMethodDecl *Method = Methods[b];
6047 unsigned NumNamedArgs = Sel.getNumArgs();
6048 // Method might have more arguments than selector indicates. This is due
6049 // to addition of c-style arguments in method.
6050 if (Method->param_size() > NumNamedArgs)
6051 NumNamedArgs = Method->param_size();
6052 if (Args.size() < NumNamedArgs)
6053 continue;
6054
6055 for (unsigned i = 0; i < NumNamedArgs; i++) {
6056 // We can't do any type-checking on a type-dependent argument.
6057 if (Args[i]->isTypeDependent()) {
6058 Match = false;
6059 break;
6060 }
6061
6062 ParmVarDecl *param = Method->parameters()[i];
6063 Expr *argExpr = Args[i];
6064 assert(argExpr && "SelectBestMethod(): missing expression");
6065
6066 // Strip the unbridged-cast placeholder expression off unless it's
6067 // a consumed argument.
6068 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6069 !param->hasAttr<CFConsumedAttr>())
6070 argExpr = stripARCUnbridgedCast(argExpr);
6071
6072 // If the parameter is __unknown_anytype, move on to the next method.
6073 if (param->getType() == Context.UnknownAnyTy) {
6074 Match = false;
6075 break;
6076 }
George Burgess IV45461812015-10-11 20:13:20 +00006077
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006078 ImplicitConversionSequence ConversionState
6079 = TryCopyInitialization(*this, argExpr, param->getType(),
6080 /*SuppressUserConversions*/false,
6081 /*InOverloadResolution=*/true,
6082 /*AllowObjCWritebackConversion=*/
6083 getLangOpts().ObjCAutoRefCount,
6084 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00006085 // This function looks for a reasonably-exact match, so we consider
6086 // incompatible pointer conversions to be a failure here.
6087 if (ConversionState.isBad() ||
6088 (ConversionState.isStandard() &&
6089 ConversionState.Standard.Second ==
6090 ICK_Incompatible_Pointer_Conversion)) {
6091 Match = false;
6092 break;
6093 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006094 }
6095 // Promote additional arguments to variadic methods.
6096 if (Match && Method->isVariadic()) {
6097 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6098 if (Args[i]->isTypeDependent()) {
6099 Match = false;
6100 break;
6101 }
6102 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6103 nullptr);
6104 if (Arg.isInvalid()) {
6105 Match = false;
6106 break;
6107 }
6108 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006109 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006110 // Check for extra arguments to non-variadic methods.
6111 if (Args.size() != NumNamedArgs)
6112 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00006113 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6114 // Special case when selectors have no argument. In this case, select
6115 // one with the most general result type of 'id'.
6116 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6117 QualType ReturnT = Methods[b]->getReturnType();
6118 if (ReturnT->isObjCIdType())
6119 return Methods[b];
6120 }
6121 }
6122 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00006123
6124 if (Match)
6125 return Method;
6126 }
6127 return nullptr;
6128}
6129
George Burgess IV2a6150d2015-10-16 01:17:38 +00006130// specific_attr_iterator iterates over enable_if attributes in reverse, and
6131// enable_if is order-sensitive. As a result, we need to reverse things
6132// sometimes. Size of 4 elements is arbitrary.
6133static SmallVector<EnableIfAttr *, 4>
6134getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6135 SmallVector<EnableIfAttr *, 4> Result;
6136 if (!Function->hasAttrs())
6137 return Result;
6138
6139 const auto &FuncAttrs = Function->getAttrs();
6140 for (Attr *Attr : FuncAttrs)
6141 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6142 Result.push_back(EnableIf);
6143
6144 std::reverse(Result.begin(), Result.end());
6145 return Result;
6146}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006147
George Burgess IV177399e2017-01-09 04:12:14 +00006148static bool
6149convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6150 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6151 bool MissingImplicitThis, Expr *&ConvertedThis,
6152 SmallVectorImpl<Expr *> &ConvertedArgs) {
6153 if (ThisArg) {
6154 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6155 assert(!isa<CXXConstructorDecl>(Method) &&
6156 "Shouldn't have `this` for ctors!");
6157 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6158 ExprResult R = S.PerformObjectArgumentInitialization(
6159 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6160 if (R.isInvalid())
6161 return false;
6162 ConvertedThis = R.get();
6163 } else {
6164 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6165 (void)MD;
6166 assert((MissingImplicitThis || MD->isStatic() ||
6167 isa<CXXConstructorDecl>(MD)) &&
6168 "Expected `this` for non-ctor instance methods");
6169 }
6170 ConvertedThis = nullptr;
6171 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006172
George Burgess IV458b3f32016-08-12 04:19:35 +00006173 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV177399e2017-01-09 04:12:14 +00006174 // user can't refer to them in the function condition.
George Burgess IV53b938d2016-08-12 04:12:31 +00006175 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6176
Nick Lewyckye283c552015-08-25 22:33:16 +00006177 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006178 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006179 ExprResult R;
George Burgess IV177399e2017-01-09 04:12:14 +00006180 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6181 S.Context, Function->getParamDecl(I)),
George Burgess IVe96abf72016-02-24 22:31:14 +00006182 SourceLocation(), Args[I]);
George Burgess IVe96abf72016-02-24 22:31:14 +00006183
George Burgess IV177399e2017-01-09 04:12:14 +00006184 if (R.isInvalid())
6185 return false;
George Burgess IVe96abf72016-02-24 22:31:14 +00006186
George Burgess IVe96abf72016-02-24 22:31:14 +00006187 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006188 }
6189
George Burgess IV177399e2017-01-09 04:12:14 +00006190 if (Trap.hasErrorOccurred())
6191 return false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006192
Nick Lewyckye283c552015-08-25 22:33:16 +00006193 // Push default arguments if needed.
6194 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6195 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6196 ParmVarDecl *P = Function->getParamDecl(i);
George Burgess IV177399e2017-01-09 04:12:14 +00006197 ExprResult R = S.PerformCopyInitialization(
6198 InitializedEntity::InitializeParameter(S.Context,
Nick Lewyckye283c552015-08-25 22:33:16 +00006199 Function->getParamDecl(i)),
6200 SourceLocation(),
6201 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6202 : P->getDefaultArg());
George Burgess IV177399e2017-01-09 04:12:14 +00006203 if (R.isInvalid())
6204 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006205 ConvertedArgs.push_back(R.get());
6206 }
6207
George Burgess IV177399e2017-01-09 04:12:14 +00006208 if (Trap.hasErrorOccurred())
6209 return false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006210 }
George Burgess IV177399e2017-01-09 04:12:14 +00006211 return true;
6212}
6213
6214EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6215 bool MissingImplicitThis) {
6216 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6217 getOrderedEnableIfAttrs(Function);
6218 if (EnableIfAttrs.empty())
6219 return nullptr;
6220
6221 SFINAETrap Trap(*this);
6222 SmallVector<Expr *, 16> ConvertedArgs;
6223 // FIXME: We should look into making enable_if late-parsed.
6224 Expr *DiscardedThis;
6225 if (!convertArgsForAvailabilityChecks(
6226 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6227 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6228 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006229
George Burgess IV2a6150d2015-10-16 01:17:38 +00006230 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006231 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006232 // FIXME: This doesn't consider value-dependent cases, because doing so is
6233 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006234 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006235 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006236 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006237
6238 if (!Result.isInt() || !Result.getInt().getBoolValue())
6239 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006240 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006241 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006242}
6243
George Burgess IV177399e2017-01-09 04:12:14 +00006244template <typename CheckFn>
George Burgess IVce6284b2017-01-28 02:19:40 +00006245static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const FunctionDecl *FD,
6246 bool ArgDependent, SourceLocation Loc,
6247 CheckFn &&IsSuccessful) {
6248 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6249 for (const auto *DIA : FD->specific_attrs<DiagnoseIfAttr>()) {
6250 if (ArgDependent == DIA->getArgDependent())
6251 Attrs.push_back(DIA);
6252 }
6253
6254 // Common case: No diagnose_if attributes, so we can quit early.
6255 if (Attrs.empty())
6256 return false;
6257
6258 auto WarningBegin = std::stable_partition(
6259 Attrs.begin(), Attrs.end(),
6260 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6261
George Burgess IV177399e2017-01-09 04:12:14 +00006262 // Note that diagnose_if attributes are late-parsed, so they appear in the
6263 // correct order (unlike enable_if attributes).
George Burgess IVce6284b2017-01-28 02:19:40 +00006264 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6265 IsSuccessful);
6266 if (ErrAttr != WarningBegin) {
6267 const DiagnoseIfAttr *DIA = *ErrAttr;
6268 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6269 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6270 << DIA->getParent() << DIA->getCond()->getSourceRange();
6271 return true;
6272 }
George Burgess IV177399e2017-01-09 04:12:14 +00006273
George Burgess IVce6284b2017-01-28 02:19:40 +00006274 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6275 if (IsSuccessful(DIA)) {
6276 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6277 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6278 << DIA->getParent() << DIA->getCond()->getSourceRange();
6279 }
6280
6281 return false;
George Burgess IV177399e2017-01-09 04:12:14 +00006282}
6283
George Burgess IVce6284b2017-01-28 02:19:40 +00006284bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6285 const Expr *ThisArg,
6286 ArrayRef<const Expr *> Args,
6287 SourceLocation Loc) {
6288 return diagnoseDiagnoseIfAttrsWith(
6289 *this, Function, /*ArgDependent=*/true, Loc,
6290 [&](const DiagnoseIfAttr *DIA) {
6291 APValue Result;
6292 // It's sane to use the same Args for any redecl of this function, since
6293 // EvaluateWithSubstitution only cares about the position of each
6294 // argument in the arg list, not the ParmVarDecl* it maps to.
6295 if (!DIA->getCond()->EvaluateWithSubstitution(
6296 Result, Context, DIA->getParent(), Args, ThisArg))
6297 return false;
6298 return Result.isInt() && Result.getInt().getBoolValue();
6299 });
George Burgess IV177399e2017-01-09 04:12:14 +00006300}
6301
George Burgess IVce6284b2017-01-28 02:19:40 +00006302bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
6303 SourceLocation Loc) {
6304 return diagnoseDiagnoseIfAttrsWith(
6305 *this, Function, /*ArgDependent=*/false, Loc,
6306 [&](const DiagnoseIfAttr *DIA) {
6307 bool Result;
6308 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6309 Result;
6310 });
George Burgess IV177399e2017-01-09 04:12:14 +00006311}
6312
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006313/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006314/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006315void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006316 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006317 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006318 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006319 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006320 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006321 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006322 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6323 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006324 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6325 QualType ObjectType;
6326 Expr::Classification ObjectClassification;
6327 if (Expr *E = Args[0]) {
6328 // Use the explit base to restrict the lookup:
6329 ObjectType = E->getType();
6330 ObjectClassification = E->Classify(Context);
6331 } // .. else there is an implit base.
John McCalla0296f72010-03-19 07:35:19 +00006332 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006333 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6334 ObjectClassification, Args.slice(1), CandidateSet,
6335 SuppressUserConversions, PartialOverloading);
6336 } else {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006337 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006338 SuppressUserConversions, PartialOverloading);
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006339 }
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006340 } else {
John McCalla0296f72010-03-19 07:35:19 +00006341 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006342 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006343 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) {
6344 QualType ObjectType;
6345 Expr::Classification ObjectClassification;
6346 if (Expr *E = Args[0]) {
6347 // Use the explit base to restrict the lookup:
6348 ObjectType = E->getType();
6349 ObjectClassification = E->Classify(Context);
6350 } // .. else there is an implit base.
George Burgess IV177399e2017-01-09 04:12:14 +00006351 AddMethodTemplateCandidate(
6352 FunTmpl, F.getPair(),
6353 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006354 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6355 Args.slice(1), CandidateSet, SuppressUserConversions,
6356 PartialOverloading);
6357 } else {
John McCalla0296f72010-03-19 07:35:19 +00006358 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006359 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006360 CandidateSet, SuppressUserConversions,
6361 PartialOverloading);
Erik Verbruggenf1898cf2017-03-28 07:22:21 +00006362 }
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006363 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006364 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006365}
6366
John McCallf0f1cf02009-11-17 07:50:12 +00006367/// AddMethodCandidate - Adds a named decl (which is some kind of
6368/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006369void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006370 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006371 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006372 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006373 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006374 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006375 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006376 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006377
6378 if (isa<UsingShadowDecl>(Decl))
6379 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006380
John McCallf0f1cf02009-11-17 07:50:12 +00006381 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6382 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6383 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006384 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006385 /*ExplicitArgs*/ nullptr, ObjectType,
6386 ObjectClassification, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006387 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006388 } else {
John McCalla0296f72010-03-19 07:35:19 +00006389 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
George Burgess IVce6284b2017-01-28 02:19:40 +00006390 ObjectType, ObjectClassification, Args, CandidateSet,
6391 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006392 }
6393}
6394
Douglas Gregor436424c2008-11-18 23:14:02 +00006395/// AddMethodCandidate - Adds the given C++ member function to the set
6396/// of candidate functions, using the given function call arguments
6397/// and the object argument (@c Object). For example, in a call
6398/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6399/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6400/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006401/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006402void
John McCalla0296f72010-03-19 07:35:19 +00006403Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006404 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006405 Expr::Classification ObjectClassification,
George Burgess IVce6284b2017-01-28 02:19:40 +00006406 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006407 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006408 bool SuppressUserConversions,
Richard Smith6eedfe72017-01-09 08:01:21 +00006409 bool PartialOverloading,
6410 ConversionSequenceList EarlyConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006411 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006412 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006413 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006414 assert(!isa<CXXConstructorDecl>(Method) &&
6415 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006416
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006417 if (!CandidateSet.isNewCandidate(Method))
6418 return;
6419
Richard Smith8b86f2d2013-11-04 01:48:18 +00006420 // C++11 [class.copy]p23: [DR1402]
6421 // A defaulted move assignment operator that is defined as deleted is
6422 // ignored by overload resolution.
6423 if (Method->isDefaulted() && Method->isDeleted() &&
6424 Method->isMoveAssignmentOperator())
6425 return;
6426
Douglas Gregor27381f32009-11-23 12:27:39 +00006427 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006428 EnterExpressionEvaluationContext Unevaluated(
6429 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006430
Douglas Gregor436424c2008-11-18 23:14:02 +00006431 // Add this candidate
Richard Smith6eedfe72017-01-09 08:01:21 +00006432 OverloadCandidate &Candidate =
6433 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
John McCalla0296f72010-03-19 07:35:19 +00006434 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006435 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006436 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006437 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006438 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006439
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006440 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006441
6442 // (C++ 13.3.2p2): A candidate function having fewer than m
6443 // parameters is viable only if it has an ellipsis in its parameter
6444 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006445 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6446 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006447 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006448 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006449 return;
6450 }
6451
6452 // (C++ 13.3.2p2): A candidate function having more than m parameters
6453 // is viable only if the (m+1)st parameter has a default argument
6454 // (8.3.6). For the purposes of overload resolution, the
6455 // parameter list is truncated on the right, so that there are
6456 // exactly m parameters.
6457 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006458 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006459 // Not enough arguments.
6460 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006461 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006462 return;
6463 }
6464
6465 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006466
John McCall6e9f8f62009-12-03 04:06:58 +00006467 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006468 // The implicit object argument is ignored.
6469 Candidate.IgnoreObjectArgument = true;
6470 else {
6471 // Determine the implicit conversion sequence for the object
6472 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006473 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6474 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6475 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006476 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006477 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006478 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006479 return;
6480 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006481 }
6482
Eli Bendersky291a57e2014-09-25 23:59:08 +00006483 // (CUDA B.1): Check for invalid calls between targets.
6484 if (getLangOpts().CUDA)
6485 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006486 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006487 Candidate.Viable = false;
6488 Candidate.FailureKind = ovl_fail_bad_target;
6489 return;
6490 }
6491
Douglas Gregor436424c2008-11-18 23:14:02 +00006492 // Determine the implicit conversion sequences for each of the
6493 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006494 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00006495 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6496 // We already formed a conversion sequence for this parameter during
6497 // template argument deduction.
6498 } else if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006499 // (C++ 13.3.2p3): for F to be a viable function, there shall
6500 // exist for each argument an implicit conversion sequence
6501 // (13.3.3.1) that converts that argument to the corresponding
6502 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006503 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006504 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006505 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006506 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006507 /*InOverloadResolution=*/true,
6508 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006509 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006510 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006511 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006512 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006513 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006514 }
6515 } else {
6516 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6517 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006518 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006519 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006520 }
6521 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006522
6523 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6524 Candidate.Viable = false;
6525 Candidate.FailureKind = ovl_fail_enable_if;
6526 Candidate.DeductionFailure.Data = FailedAttr;
6527 return;
6528 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006529}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006530
Douglas Gregor97628d62009-08-21 00:16:32 +00006531/// \brief Add a C++ member function template as a candidate to the candidate
6532/// set, using template argument deduction to produce an appropriate member
6533/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006534void
Douglas Gregor97628d62009-08-21 00:16:32 +00006535Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006536 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006537 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006538 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006539 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006540 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006541 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006542 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006543 bool SuppressUserConversions,
6544 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006545 if (!CandidateSet.isNewCandidate(MethodTmpl))
6546 return;
6547
Douglas Gregor97628d62009-08-21 00:16:32 +00006548 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006549 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006550 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006551 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006552 // candidate functions in the usual way.113) A given name can refer to one
6553 // or more function templates and also to a set of overloaded non-template
6554 // functions. In such a case, the candidate functions generated from each
6555 // function template are combined with the set of non-template candidate
6556 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006557 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006558 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006559 ConversionSequenceList Conversions;
6560 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6561 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6562 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6563 return CheckNonDependentConversions(
6564 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6565 SuppressUserConversions, ActingContext, ObjectType,
6566 ObjectClassification);
6567 })) {
6568 OverloadCandidate &Candidate =
6569 CandidateSet.addCandidate(Conversions.size(), Conversions);
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006570 Candidate.FoundDecl = FoundDecl;
6571 Candidate.Function = MethodTmpl->getTemplatedDecl();
6572 Candidate.Viable = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006573 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006574 Candidate.IgnoreObjectArgument =
6575 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6576 ObjectType.isNull();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006577 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006578 if (Result == TDK_NonDependentConversionFailure)
6579 Candidate.FailureKind = ovl_fail_bad_conversion;
6580 else {
6581 Candidate.FailureKind = ovl_fail_bad_deduction;
6582 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6583 Info);
6584 }
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006585 return;
6586 }
Mike Stump11289f42009-09-09 15:08:12 +00006587
Douglas Gregor97628d62009-08-21 00:16:32 +00006588 // Add the function template specialization produced by template argument
6589 // deduction as a candidate.
6590 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006591 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006592 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006593 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
George Burgess IVce6284b2017-01-28 02:19:40 +00006594 ActingContext, ObjectType, ObjectClassification, Args,
6595 CandidateSet, SuppressUserConversions, PartialOverloading,
6596 Conversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00006597}
6598
Douglas Gregor05155d82009-08-21 23:19:43 +00006599/// \brief Add a C++ function template specialization as a candidate
6600/// in the candidate set, using template argument deduction to produce
6601/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006602void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006603Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006604 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006605 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006606 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006607 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006608 bool SuppressUserConversions,
6609 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006610 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6611 return;
6612
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006613 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006614 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006615 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006616 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006617 // candidate functions in the usual way.113) A given name can refer to one
6618 // or more function templates and also to a set of overloaded non-template
6619 // functions. In such a case, the candidate functions generated from each
6620 // function template are combined with the set of non-template candidate
6621 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006622 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006623 FunctionDecl *Specialization = nullptr;
Richard Smith6eedfe72017-01-09 08:01:21 +00006624 ConversionSequenceList Conversions;
6625 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6626 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6627 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6628 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6629 Args, CandidateSet, Conversions,
6630 SuppressUserConversions);
6631 })) {
6632 OverloadCandidate &Candidate =
6633 CandidateSet.addCandidate(Conversions.size(), Conversions);
John McCalla0296f72010-03-19 07:35:19 +00006634 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006635 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6636 Candidate.Viable = false;
6637 Candidate.IsSurrogate = false;
Richard Smith9d05e152017-01-10 20:52:50 +00006638 // Ignore the object argument if there is one, since we don't have an object
6639 // type.
6640 Candidate.IgnoreObjectArgument =
6641 isa<CXXMethodDecl>(Candidate.Function) &&
6642 !isa<CXXConstructorDecl>(Candidate.Function);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006643 Candidate.ExplicitCallArguments = Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00006644 if (Result == TDK_NonDependentConversionFailure)
6645 Candidate.FailureKind = ovl_fail_bad_conversion;
6646 else {
6647 Candidate.FailureKind = ovl_fail_bad_deduction;
6648 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6649 Info);
6650 }
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006651 return;
6652 }
Mike Stump11289f42009-09-09 15:08:12 +00006653
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006654 // Add the function template specialization produced by template argument
6655 // deduction as a candidate.
6656 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006657 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Richard Smith6eedfe72017-01-09 08:01:21 +00006658 SuppressUserConversions, PartialOverloading,
6659 /*AllowExplicit*/false, Conversions);
6660}
6661
6662/// Check that implicit conversion sequences can be formed for each argument
6663/// whose corresponding parameter has a non-dependent type, per DR1391's
6664/// [temp.deduct.call]p10.
6665bool Sema::CheckNonDependentConversions(
6666 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6667 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6668 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6669 CXXRecordDecl *ActingContext, QualType ObjectType,
6670 Expr::Classification ObjectClassification) {
6671 // FIXME: The cases in which we allow explicit conversions for constructor
6672 // arguments never consider calling a constructor template. It's not clear
6673 // that is correct.
6674 const bool AllowExplicit = false;
6675
6676 auto *FD = FunctionTemplate->getTemplatedDecl();
6677 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6678 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6679 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6680
6681 Conversions =
6682 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6683
6684 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006685 EnterExpressionEvaluationContext Unevaluated(
6686 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith6eedfe72017-01-09 08:01:21 +00006687
6688 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6689 // require that, but this check should never result in a hard error, and
6690 // overload resolution is permitted to sidestep instantiations.
6691 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6692 !ObjectType.isNull()) {
6693 Conversions[0] = TryObjectArgumentInitialization(
6694 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6695 Method, ActingContext);
6696 if (Conversions[0].isBad())
6697 return true;
6698 }
6699
6700 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6701 ++I) {
6702 QualType ParamType = ParamTypes[I];
6703 if (!ParamType->isDependentType()) {
6704 Conversions[ThisConversions + I]
6705 = TryCopyInitialization(*this, Args[I], ParamType,
6706 SuppressUserConversions,
6707 /*InOverloadResolution=*/true,
6708 /*AllowObjCWritebackConversion=*/
6709 getLangOpts().ObjCAutoRefCount,
6710 AllowExplicit);
6711 if (Conversions[ThisConversions + I].isBad())
6712 return true;
6713 }
6714 }
6715
6716 return false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006717}
Mike Stump11289f42009-09-09 15:08:12 +00006718
Douglas Gregor4b60a152013-11-07 22:34:54 +00006719/// Determine whether this is an allowable conversion from the result
6720/// of an explicit conversion operator to the expected type, per C++
6721/// [over.match.conv]p1 and [over.match.ref]p1.
6722///
6723/// \param ConvType The return type of the conversion function.
6724///
6725/// \param ToType The type we are converting to.
6726///
6727/// \param AllowObjCPointerConversion Allow a conversion from one
6728/// Objective-C pointer to another.
6729///
6730/// \returns true if the conversion is allowable, false otherwise.
6731static bool isAllowableExplicitConversion(Sema &S,
6732 QualType ConvType, QualType ToType,
6733 bool AllowObjCPointerConversion) {
6734 QualType ToNonRefType = ToType.getNonReferenceType();
6735
6736 // Easy case: the types are the same.
6737 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6738 return true;
6739
6740 // Allow qualification conversions.
6741 bool ObjCLifetimeConversion;
6742 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6743 ObjCLifetimeConversion))
6744 return true;
6745
6746 // If we're not allowed to consider Objective-C pointer conversions,
6747 // we're done.
6748 if (!AllowObjCPointerConversion)
6749 return false;
6750
6751 // Is this an Objective-C pointer conversion?
6752 bool IncompatibleObjC = false;
6753 QualType ConvertedType;
6754 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6755 IncompatibleObjC);
6756}
6757
Douglas Gregora1f013e2008-11-07 22:36:19 +00006758/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006759/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006760/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006761/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006762/// (which may or may not be the same type as the type that the
6763/// conversion function produces).
6764void
6765Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006766 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006767 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006768 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006769 OverloadCandidateSet& CandidateSet,
6770 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006771 assert(!Conversion->getDescribedFunctionTemplate() &&
6772 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006773 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006774 if (!CandidateSet.isNewCandidate(Conversion))
6775 return;
6776
Richard Smith2a7d4812013-05-04 07:00:32 +00006777 // If the conversion function has an undeduced return type, trigger its
6778 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006779 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006780 if (DeduceReturnType(Conversion, From->getExprLoc()))
6781 return;
6782 ConvType = Conversion->getConversionType().getNonReferenceType();
6783 }
6784
Richard Smith089c3162013-09-21 21:55:46 +00006785 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6786 // operator is only a candidate if its return type is the target type or
6787 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006788 if (Conversion->isExplicit() &&
6789 !isAllowableExplicitConversion(*this, ConvType, ToType,
6790 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006791 return;
6792
Douglas Gregor27381f32009-11-23 12:27:39 +00006793 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006794 EnterExpressionEvaluationContext Unevaluated(
6795 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006796
Douglas Gregora1f013e2008-11-07 22:36:19 +00006797 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006798 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006799 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006800 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006801 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006802 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006803 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006804 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006805 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006806 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006807 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006808
Douglas Gregor6affc782010-08-19 15:37:02 +00006809 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006810 // For conversion functions, the function is considered to be a member of
6811 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006812 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006813 //
6814 // Determine the implicit conversion sequence for the implicit
6815 // object parameter.
6816 QualType ImplicitParamType = From->getType();
6817 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6818 ImplicitParamType = FromPtrType->getPointeeType();
6819 CXXRecordDecl *ConversionContext
6820 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006821
Richard Smith0f59cb32015-12-18 21:45:41 +00006822 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6823 *this, CandidateSet.getLocation(), From->getType(),
6824 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006825
John McCall0d1da222010-01-12 00:44:57 +00006826 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006827 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006828 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006829 return;
6830 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006831
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006832 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006833 // derived to base as such conversions are given Conversion Rank. They only
6834 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6835 QualType FromCanon
6836 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6837 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006838 if (FromCanon == ToCanon ||
6839 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006840 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006841 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006842 return;
6843 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006844
Douglas Gregora1f013e2008-11-07 22:36:19 +00006845 // To determine what the conversion from the result of calling the
6846 // conversion function to the type we're eventually trying to
6847 // convert to (ToType), we need to synthesize a call to the
6848 // conversion function and attempt copy initialization from it. This
6849 // makes sure that we get the right semantics with respect to
6850 // lvalues/rvalues and the type. Fortunately, we can allocate this
6851 // call on the stack and we don't need its arguments to be
6852 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006853 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006854 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006855 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6856 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006857 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006858 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006859
Richard Smith48d24642011-07-13 22:53:21 +00006860 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006861 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006862 Candidate.Viable = false;
6863 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6864 return;
6865 }
6866
Richard Smith48d24642011-07-13 22:53:21 +00006867 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006868
Mike Stump11289f42009-09-09 15:08:12 +00006869 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006870 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6871 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006872 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006873 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006874 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006875 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006876 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006877 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006878 /*InOverloadResolution=*/false,
6879 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006880
John McCall0d1da222010-01-12 00:44:57 +00006881 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006882 case ImplicitConversionSequence::StandardConversion:
6883 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006884
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006885 // C++ [over.ics.user]p3:
6886 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006887 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006888 // shall have exact match rank.
6889 if (Conversion->getPrimaryTemplate() &&
6890 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6891 Candidate.Viable = false;
6892 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006893 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006895
Douglas Gregorcba72b12011-01-21 05:18:22 +00006896 // C++0x [dcl.init.ref]p5:
6897 // In the second case, if the reference is an rvalue reference and
6898 // the second standard conversion sequence of the user-defined
6899 // conversion sequence includes an lvalue-to-rvalue conversion, the
6900 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006901 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006902 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6903 Candidate.Viable = false;
6904 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006905 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006906 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006907 break;
6908
6909 case ImplicitConversionSequence::BadConversion:
6910 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006911 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006912 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006913
6914 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006915 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006916 "Can only end up with a standard conversion sequence or failure");
6917 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006918
Craig Topper5fc8fc22014-08-27 06:28:36 +00006919 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006920 Candidate.Viable = false;
6921 Candidate.FailureKind = ovl_fail_enable_if;
6922 Candidate.DeductionFailure.Data = FailedAttr;
6923 return;
6924 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006925}
6926
Douglas Gregor05155d82009-08-21 23:19:43 +00006927/// \brief Adds a conversion function template specialization
6928/// candidate to the overload set, using template argument deduction
6929/// to deduce the template arguments of the conversion function
6930/// template from the type that we are converting to (C++
6931/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006932void
Douglas Gregor05155d82009-08-21 23:19:43 +00006933Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006934 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006935 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006936 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006937 OverloadCandidateSet &CandidateSet,
6938 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006939 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6940 "Only conversion function templates permitted here");
6941
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006942 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6943 return;
6944
Craig Toppere6706e42012-09-19 02:26:47 +00006945 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006946 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006947 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006948 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006949 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006950 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006951 Candidate.FoundDecl = FoundDecl;
6952 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6953 Candidate.Viable = false;
6954 Candidate.FailureKind = ovl_fail_bad_deduction;
6955 Candidate.IsSurrogate = false;
6956 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006957 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006958 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006959 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006960 return;
6961 }
Mike Stump11289f42009-09-09 15:08:12 +00006962
Douglas Gregor05155d82009-08-21 23:19:43 +00006963 // Add the conversion function template specialization produced by
6964 // template argument deduction as a candidate.
6965 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006966 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006967 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006968}
6969
Douglas Gregorab7897a2008-11-19 22:57:39 +00006970/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6971/// converts the given @c Object to a function pointer via the
6972/// conversion function @c Conversion, and then attempts to call it
6973/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6974/// the type of function that we'll eventually be calling.
6975void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006976 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006977 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006978 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006979 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006980 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006981 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006982 if (!CandidateSet.isNewCandidate(Conversion))
6983 return;
6984
Douglas Gregor27381f32009-11-23 12:27:39 +00006985 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00006986 EnterExpressionEvaluationContext Unevaluated(
6987 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006988
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006989 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006990 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006991 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006992 Candidate.Surrogate = Conversion;
6993 Candidate.Viable = true;
6994 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006995 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006996 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006997
6998 // Determine the implicit conversion sequence for the implicit
6999 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00007000 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7001 *this, CandidateSet.getLocation(), Object->getType(),
7002 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00007003 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007004 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007005 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00007006 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007007 return;
7008 }
7009
7010 // The first conversion is actually a user-defined conversion whose
7011 // first conversion is ObjectInit's standard conversion (which is
7012 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00007013 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007014 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00007015 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007016 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007017 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00007018 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00007019 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00007020 = Candidate.Conversions[0].UserDefined.Before;
7021 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7022
Mike Stump11289f42009-09-09 15:08:12 +00007023 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007024 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007025
7026 // (C++ 13.3.2p2): A candidate function having fewer than m
7027 // parameters is viable only if it has an ellipsis in its parameter
7028 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007029 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007030 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007031 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007032 return;
7033 }
7034
7035 // Function types don't have any default arguments, so just check if
7036 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007037 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007038 // Not enough arguments.
7039 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007040 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007041 return;
7042 }
7043
7044 // Determine the implicit conversion sequences for each of the
7045 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00007046 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007047 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007048 // (C++ 13.3.2p3): for F to be a viable function, there shall
7049 // exist for each argument an implicit conversion sequence
7050 // (13.3.3.1) that converts that argument to the corresponding
7051 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00007052 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00007053 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007054 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00007055 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00007056 /*InOverloadResolution=*/false,
7057 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007058 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00007059 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00007060 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007061 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007062 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007063 }
7064 } else {
7065 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7066 // argument for which there is no corresponding parameter is
7067 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00007068 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007069 }
7070 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007071
Craig Topper5fc8fc22014-08-27 06:28:36 +00007072 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007073 Candidate.Viable = false;
7074 Candidate.FailureKind = ovl_fail_enable_if;
7075 Candidate.DeductionFailure.Data = FailedAttr;
7076 return;
7077 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00007078}
7079
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007080/// \brief Add overload candidates for overloaded operators that are
7081/// member functions.
7082///
7083/// Add the overloaded operator candidates that are member functions
7084/// for the operator Op that was used in an operator expression such
7085/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7086/// CandidateSet will store the added overload candidates. (C++
7087/// [over.match.oper]).
7088void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7089 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00007090 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007091 OverloadCandidateSet& CandidateSet,
7092 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00007093 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7094
7095 // C++ [over.match.oper]p3:
7096 // For a unary operator @ with an operand of a type whose
7097 // cv-unqualified version is T1, and for a binary operator @ with
7098 // a left operand of a type whose cv-unqualified version is T1 and
7099 // a right operand of a type whose cv-unqualified version is T2,
7100 // three sets of candidate functions, designated member
7101 // candidates, non-member candidates and built-in candidates, are
7102 // constructed as follows:
7103 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00007104
Richard Smith0feaf0c2013-04-20 12:41:22 +00007105 // -- If T1 is a complete class type or a class currently being
7106 // defined, the set of member candidates is the result of the
7107 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7108 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007109 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00007110 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00007111 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00007112 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00007113 // If the type is neither complete nor being defined, bail out now.
7114 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007115 return;
Mike Stump11289f42009-09-09 15:08:12 +00007116
John McCall27b18f82009-11-17 02:14:36 +00007117 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7118 LookupQualifiedName(Operators, T1Rec->getDecl());
7119 Operators.suppressDiagnostics();
7120
Mike Stump11289f42009-09-09 15:08:12 +00007121 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00007122 OperEnd = Operators.end();
7123 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00007124 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00007125 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +00007126 Args[0]->Classify(Context), Args.slice(1),
George Burgess IV177399e2017-01-09 04:12:14 +00007127 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00007128 }
Douglas Gregor436424c2008-11-18 23:14:02 +00007129}
7130
Douglas Gregora11693b2008-11-12 17:17:38 +00007131/// AddBuiltinCandidate - Add a candidate for a built-in
7132/// operator. ResultTy and ParamTys are the result and parameter types
7133/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00007134/// arguments being passed to the candidate. IsAssignmentOperator
7135/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00007136/// operator. NumContextualBoolArguments is the number of arguments
7137/// (at the beginning of the argument list) that will be contextually
7138/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00007139void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00007140 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00007141 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007142 bool IsAssignmentOperator,
7143 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00007144 // Overload resolution is always an unevaluated context.
Faisal Valid143a0c2017-04-01 21:30:49 +00007145 EnterExpressionEvaluationContext Unevaluated(
7146 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00007147
Douglas Gregora11693b2008-11-12 17:17:38 +00007148 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00007149 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00007150 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7151 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00007152 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007153 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00007154 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007155 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00007156 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
7157
7158 // Determine the implicit conversion sequences for each of the
7159 // arguments.
7160 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00007161 Candidate.ExplicitCallArguments = Args.size();
7162 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00007163 // C++ [over.match.oper]p4:
7164 // For the built-in assignment operators, conversions of the
7165 // left operand are restricted as follows:
7166 // -- no temporaries are introduced to hold the left operand, and
7167 // -- no user-defined conversions are applied to the left
7168 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00007169 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00007170 //
7171 // We block these conversions by turning off user-defined
7172 // conversions, since that is the only way that initialization of
7173 // a reference to a non-class type can occur from something that
7174 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007175 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00007176 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00007177 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00007178 Candidate.Conversions[ArgIdx]
7179 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007180 } else {
Mike Stump11289f42009-09-09 15:08:12 +00007181 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007182 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00007183 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00007184 /*InOverloadResolution=*/false,
7185 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00007186 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00007187 }
John McCall0d1da222010-01-12 00:44:57 +00007188 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007189 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00007190 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00007191 break;
7192 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007193 }
7194}
7195
Craig Toppercd7b0332013-07-01 06:29:40 +00007196namespace {
7197
Douglas Gregora11693b2008-11-12 17:17:38 +00007198/// BuiltinCandidateTypeSet - A set of types that will be used for the
7199/// candidate operator functions for built-in operators (C++
7200/// [over.built]). The types are separated into pointer types and
7201/// enumeration types.
7202class BuiltinCandidateTypeSet {
7203 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00007204 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7205 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00007206
7207 /// PointerTypes - The set of pointer types that will be used in the
7208 /// built-in candidates.
7209 TypeSet PointerTypes;
7210
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007211 /// MemberPointerTypes - The set of member pointer types that will be
7212 /// used in the built-in candidates.
7213 TypeSet MemberPointerTypes;
7214
Douglas Gregora11693b2008-11-12 17:17:38 +00007215 /// EnumerationTypes - The set of enumeration types that will be
7216 /// used in the built-in candidates.
7217 TypeSet EnumerationTypes;
7218
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007219 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007220 /// candidates.
7221 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00007222
7223 /// \brief A flag indicating non-record types are viable candidates
7224 bool HasNonRecordTypes;
7225
7226 /// \brief A flag indicating whether either arithmetic or enumeration types
7227 /// were present in the candidate set.
7228 bool HasArithmeticOrEnumeralTypes;
7229
Douglas Gregor80af3132011-05-21 23:15:46 +00007230 /// \brief A flag indicating whether the nullptr type was present in the
7231 /// candidate set.
7232 bool HasNullPtrType;
7233
Douglas Gregor8a2e6012009-08-24 15:23:48 +00007234 /// Sema - The semantic analysis instance where we are building the
7235 /// candidate type set.
7236 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00007237
Douglas Gregora11693b2008-11-12 17:17:38 +00007238 /// Context - The AST context in which we will build the type sets.
7239 ASTContext &Context;
7240
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007241 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7242 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007243 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00007244
7245public:
7246 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00007247 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00007248
Mike Stump11289f42009-09-09 15:08:12 +00007249 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00007250 : HasNonRecordTypes(false),
7251 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00007252 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00007253 SemaRef(SemaRef),
7254 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00007255
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007256 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007257 SourceLocation Loc,
7258 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007259 bool AllowExplicitConversions,
7260 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007261
7262 /// pointer_begin - First pointer type found;
7263 iterator pointer_begin() { return PointerTypes.begin(); }
7264
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007265 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007266 iterator pointer_end() { return PointerTypes.end(); }
7267
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007268 /// member_pointer_begin - First member pointer type found;
7269 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7270
7271 /// member_pointer_end - Past the last member pointer type found;
7272 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7273
Douglas Gregora11693b2008-11-12 17:17:38 +00007274 /// enumeration_begin - First enumeration type found;
7275 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7276
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007277 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00007278 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007279
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007280 iterator vector_begin() { return VectorTypes.begin(); }
7281 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00007282
7283 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7284 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00007285 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00007286};
7287
Craig Toppercd7b0332013-07-01 06:29:40 +00007288} // end anonymous namespace
7289
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007290/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00007291/// the set of pointer types along with any more-qualified variants of
7292/// that type. For example, if @p Ty is "int const *", this routine
7293/// will add "int const *", "int const volatile *", "int const
7294/// restrict *", and "int const volatile restrict *" to the set of
7295/// pointer types. Returns true if the add of @p Ty itself succeeded,
7296/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007297///
7298/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007299bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007300BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7301 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00007302
Douglas Gregora11693b2008-11-12 17:17:38 +00007303 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007304 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00007305 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007306
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007307 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00007308 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007309 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007310 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007311 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7312 PointeeTy = PTy->getPointeeType();
7313 buildObjCPtr = true;
7314 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007315 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00007316 }
7317
Sebastian Redl4990a632009-11-18 20:39:26 +00007318 // Don't add qualified variants of arrays. For one, they're not allowed
7319 // (the qualifier would sink to the element type), and for another, the
7320 // only overload situation where it matters is subscript or pointer +- int,
7321 // and those shouldn't have qualifier variants anyway.
7322 if (PointeeTy->isArrayType())
7323 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007324
John McCall8ccfcb52009-09-24 19:53:00 +00007325 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007326 bool hasVolatile = VisibleQuals.hasVolatile();
7327 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007328
John McCall8ccfcb52009-09-24 19:53:00 +00007329 // Iterate through all strict supersets of BaseCVR.
7330 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7331 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007332 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007333 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00007334
7335 // Skip over restrict if no restrict found anywhere in the types, or if
7336 // the type cannot be restrict-qualified.
7337 if ((CVR & Qualifiers::Restrict) &&
7338 (!hasRestrict ||
7339 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7340 continue;
7341
7342 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007343 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007344
7345 // Build qualified pointer type.
7346 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007347 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007348 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007349 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007350 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7351
7352 // Insert qualified pointer type.
7353 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007354 }
7355
7356 return true;
7357}
7358
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007359/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7360/// to the set of pointer types along with any more-qualified variants of
7361/// that type. For example, if @p Ty is "int const *", this routine
7362/// will add "int const *", "int const volatile *", "int const
7363/// restrict *", and "int const volatile restrict *" to the set of
7364/// pointer types. Returns true if the add of @p Ty itself succeeded,
7365/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007366///
7367/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007368bool
7369BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7370 QualType Ty) {
7371 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007372 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007373 return false;
7374
John McCall8ccfcb52009-09-24 19:53:00 +00007375 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7376 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007377
John McCall8ccfcb52009-09-24 19:53:00 +00007378 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007379 // Don't add qualified variants of arrays. For one, they're not allowed
7380 // (the qualifier would sink to the element type), and for another, the
7381 // only overload situation where it matters is subscript or pointer +- int,
7382 // and those shouldn't have qualifier variants anyway.
7383 if (PointeeTy->isArrayType())
7384 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007385 const Type *ClassTy = PointerTy->getClass();
7386
7387 // Iterate through all strict supersets of the pointee type's CVR
7388 // qualifiers.
7389 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7390 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7391 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007392
John McCall8ccfcb52009-09-24 19:53:00 +00007393 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007394 MemberPointerTypes.insert(
7395 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007396 }
7397
7398 return true;
7399}
7400
Douglas Gregora11693b2008-11-12 17:17:38 +00007401/// AddTypesConvertedFrom - Add each of the types to which the type @p
7402/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007403/// primarily interested in pointer types and enumeration types. We also
7404/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007405/// AllowUserConversions is true if we should look at the conversion
7406/// functions of a class type, and AllowExplicitConversions if we
7407/// should also include the explicit conversion functions of a class
7408/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007409void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007410BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007411 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007412 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007413 bool AllowExplicitConversions,
7414 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007415 // Only deal with canonical types.
7416 Ty = Context.getCanonicalType(Ty);
7417
7418 // Look through reference types; they aren't part of the type of an
7419 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007420 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007421 Ty = RefTy->getPointeeType();
7422
John McCall33ddac02011-01-19 10:06:00 +00007423 // If we're dealing with an array type, decay to the pointer.
7424 if (Ty->isArrayType())
7425 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7426
7427 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007428 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007429
Chandler Carruth00a38332010-12-13 01:44:01 +00007430 // Flag if we ever add a non-record type.
7431 const RecordType *TyRec = Ty->getAs<RecordType>();
7432 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7433
Chandler Carruth00a38332010-12-13 01:44:01 +00007434 // Flag if we encounter an arithmetic type.
7435 HasArithmeticOrEnumeralTypes =
7436 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7437
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007438 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7439 PointerTypes.insert(Ty);
7440 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007441 // Insert our type, and its more-qualified variants, into the set
7442 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007443 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007444 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007445 } else if (Ty->isMemberPointerType()) {
7446 // Member pointers are far easier, since the pointee can't be converted.
7447 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7448 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007449 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007450 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007451 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007452 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007453 // We treat vector types as arithmetic types in many contexts as an
7454 // extension.
7455 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007456 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007457 } else if (Ty->isNullPtrType()) {
7458 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007459 } else if (AllowUserConversions && TyRec) {
7460 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007461 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007462 return;
Mike Stump11289f42009-09-09 15:08:12 +00007463
Chandler Carruth00a38332010-12-13 01:44:01 +00007464 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007465 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007466 if (isa<UsingShadowDecl>(D))
7467 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007468
Chandler Carruth00a38332010-12-13 01:44:01 +00007469 // Skip conversion function templates; they don't tell us anything
7470 // about which builtin types we can convert to.
7471 if (isa<FunctionTemplateDecl>(D))
7472 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007473
Chandler Carruth00a38332010-12-13 01:44:01 +00007474 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7475 if (AllowExplicitConversions || !Conv->isExplicit()) {
7476 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7477 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007478 }
7479 }
7480 }
7481}
7482
Douglas Gregor84605ae2009-08-24 13:43:27 +00007483/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7484/// the volatile- and non-volatile-qualified assignment operators for the
7485/// given type to the candidate set.
7486static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7487 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007488 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007489 OverloadCandidateSet &CandidateSet) {
7490 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007491
Douglas Gregor84605ae2009-08-24 13:43:27 +00007492 // T& operator=(T&, T)
7493 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7494 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007495 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007496 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007497
Douglas Gregor84605ae2009-08-24 13:43:27 +00007498 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7499 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007500 ParamTypes[0]
7501 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007502 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007503 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007504 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007505 }
7506}
Mike Stump11289f42009-09-09 15:08:12 +00007507
Sebastian Redl1054fae2009-10-25 17:03:50 +00007508/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7509/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007510static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7511 Qualifiers VRQuals;
7512 const RecordType *TyRec;
7513 if (const MemberPointerType *RHSMPType =
7514 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007515 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007516 else
7517 TyRec = ArgExpr->getType()->getAs<RecordType>();
7518 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007519 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007520 VRQuals.addVolatile();
7521 VRQuals.addRestrict();
7522 return VRQuals;
7523 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007524
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007525 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007526 if (!ClassDecl->hasDefinition())
7527 return VRQuals;
7528
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007529 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007530 if (isa<UsingShadowDecl>(D))
7531 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7532 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007533 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7534 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7535 CanTy = ResTypeRef->getPointeeType();
7536 // Need to go down the pointer/mempointer chain and add qualifiers
7537 // as see them.
7538 bool done = false;
7539 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007540 if (CanTy.isRestrictQualified())
7541 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007542 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7543 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007544 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007545 CanTy->getAs<MemberPointerType>())
7546 CanTy = ResTypeMPtr->getPointeeType();
7547 else
7548 done = true;
7549 if (CanTy.isVolatileQualified())
7550 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007551 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7552 return VRQuals;
7553 }
7554 }
7555 }
7556 return VRQuals;
7557}
John McCall52872982010-11-13 05:51:15 +00007558
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007559namespace {
John McCall52872982010-11-13 05:51:15 +00007560
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007561/// \brief Helper class to manage the addition of builtin operator overload
7562/// candidates. It provides shared state and utility methods used throughout
7563/// the process, as well as a helper method to add each group of builtin
7564/// operator overloads from the standard to a candidate set.
7565class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007566 // Common instance state available to all overload candidate addition methods.
7567 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007568 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007569 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007570 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007571 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007572 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007573
Chandler Carruthc6586e52010-12-12 10:35:00 +00007574 // Define some constants used to index and iterate over the arithemetic types
7575 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007576 // The "promoted arithmetic types" are the arithmetic
7577 // types are that preserved by promotion (C++ [over.built]p2).
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007578 static const unsigned FirstIntegralType = 4;
7579 static const unsigned LastIntegralType = 21;
7580 static const unsigned FirstPromotedIntegralType = 4,
7581 LastPromotedIntegralType = 12;
John McCall52872982010-11-13 05:51:15 +00007582 static const unsigned FirstPromotedArithmeticType = 0,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007583 LastPromotedArithmeticType = 12;
7584 static const unsigned NumArithmeticTypes = 21;
John McCall52872982010-11-13 05:51:15 +00007585
Chandler Carruthc6586e52010-12-12 10:35:00 +00007586 /// \brief Get the canonical type for a given arithmetic type index.
7587 CanQualType getArithmeticType(unsigned index) {
7588 assert(index < NumArithmeticTypes);
7589 static CanQualType ASTContext::* const
7590 ArithmeticTypes[NumArithmeticTypes] = {
7591 // Start of promoted types.
7592 &ASTContext::FloatTy,
7593 &ASTContext::DoubleTy,
7594 &ASTContext::LongDoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007595 &ASTContext::Float128Ty,
John McCall52872982010-11-13 05:51:15 +00007596
Chandler Carruthc6586e52010-12-12 10:35:00 +00007597 // Start of integral types.
7598 &ASTContext::IntTy,
7599 &ASTContext::LongTy,
7600 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007601 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007602 &ASTContext::UnsignedIntTy,
7603 &ASTContext::UnsignedLongTy,
7604 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007605 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007606 // End of promoted types.
7607
7608 &ASTContext::BoolTy,
7609 &ASTContext::CharTy,
7610 &ASTContext::WCharTy,
7611 &ASTContext::Char16Ty,
7612 &ASTContext::Char32Ty,
7613 &ASTContext::SignedCharTy,
7614 &ASTContext::ShortTy,
7615 &ASTContext::UnsignedCharTy,
7616 &ASTContext::UnsignedShortTy,
7617 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007618 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007619 };
7620 return S.Context.*ArithmeticTypes[index];
7621 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007622
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007623 /// \brief Gets the canonical type resulting from the usual arithemetic
7624 /// converions for the given arithmetic types.
7625 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7626 // Accelerator table for performing the usual arithmetic conversions.
7627 // The rules are basically:
7628 // - if either is floating-point, use the wider floating-point
7629 // - if same signedness, use the higher rank
7630 // - if same size, use unsigned of the higher rank
7631 // - use the larger type
7632 // These rules, together with the axiom that higher ranks are
7633 // never smaller, are sufficient to precompute all of these results
7634 // *except* when dealing with signed types of higher rank.
7635 // (we could precompute SLL x UI for all known platforms, but it's
7636 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007637 // We assume that int128 has a higher rank than long long on all platforms.
George Burgess IVf23ce362016-04-29 21:32:53 +00007638 enum PromotedType : int8_t {
Richard Smith521ecc12012-06-10 08:00:26 +00007639 Dep=-1,
7640 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007641 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007642 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007643 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007644/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7645/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7646/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7647/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7648/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7649/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7650/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7651/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7652/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7653/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7654/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007655 };
7656
7657 assert(L < LastPromotedArithmeticType);
7658 assert(R < LastPromotedArithmeticType);
7659 int Idx = ConversionsTable[L][R];
7660
7661 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007662 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007663
7664 // Slow path: we need to compare widths.
7665 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007666 CanQualType LT = getArithmeticType(L),
7667 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007668 unsigned LW = S.Context.getIntWidth(LT),
7669 RW = S.Context.getIntWidth(RT);
7670
7671 // If they're different widths, use the signed type.
7672 if (LW > RW) return LT;
7673 else if (LW < RW) return RT;
7674
7675 // Otherwise, use the unsigned type of the signed type's rank.
7676 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7677 assert(L == SLL || R == SLL);
7678 return S.Context.UnsignedLongLongTy;
7679 }
7680
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007681 /// \brief Helper method to factor out the common pattern of adding overloads
7682 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007683 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007684 bool HasVolatile,
7685 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007686 QualType ParamTypes[2] = {
7687 S.Context.getLValueReferenceType(CandidateTy),
7688 S.Context.IntTy
7689 };
7690
7691 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007692 if (Args.size() == 1)
7693 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007694 else
Richard Smithe54c3072013-05-05 15:51:06 +00007695 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007696
7697 // Use a heuristic to reduce number of builtin candidates in the set:
7698 // add volatile version only if there are conversions to a volatile type.
7699 if (HasVolatile) {
7700 ParamTypes[0] =
7701 S.Context.getLValueReferenceType(
7702 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007703 if (Args.size() == 1)
7704 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007705 else
Richard Smithe54c3072013-05-05 15:51:06 +00007706 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007707 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007708
7709 // Add restrict version only if there are conversions to a restrict type
7710 // and our candidate type is a non-restrict-qualified pointer.
7711 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7712 !CandidateTy.isRestrictQualified()) {
7713 ParamTypes[0]
7714 = S.Context.getLValueReferenceType(
7715 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007716 if (Args.size() == 1)
7717 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007718 else
Richard Smithe54c3072013-05-05 15:51:06 +00007719 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007720
7721 if (HasVolatile) {
7722 ParamTypes[0]
7723 = S.Context.getLValueReferenceType(
7724 S.Context.getCVRQualifiedType(CandidateTy,
7725 (Qualifiers::Volatile |
7726 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007727 if (Args.size() == 1)
7728 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007729 else
Richard Smithe54c3072013-05-05 15:51:06 +00007730 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007731 }
7732 }
7733
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007734 }
7735
7736public:
7737 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007738 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007739 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007740 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007741 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007742 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007743 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007744 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007745 HasArithmeticOrEnumeralCandidateType(
7746 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007747 CandidateTypes(CandidateTypes),
7748 CandidateSet(CandidateSet) {
7749 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007750 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007751 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007752 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007753 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007754 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007755 assert(getArithmeticType(FirstPromotedArithmeticType)
7756 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007757 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007758 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007759 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007760 "Invalid last promoted arithmetic type");
7761 }
7762
7763 // C++ [over.built]p3:
7764 //
7765 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7766 // is either volatile or empty, there exist candidate operator
7767 // functions of the form
7768 //
7769 // VQ T& operator++(VQ T&);
7770 // T operator++(VQ T&, int);
7771 //
7772 // C++ [over.built]p4:
7773 //
7774 // For every pair (T, VQ), where T is an arithmetic type other
7775 // than bool, and VQ is either volatile or empty, there exist
7776 // candidate operator functions of the form
7777 //
7778 // VQ T& operator--(VQ T&);
7779 // T operator--(VQ T&, int);
7780 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007781 if (!HasArithmeticOrEnumeralCandidateType)
7782 return;
7783
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007784 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7785 Arith < NumArithmeticTypes; ++Arith) {
7786 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007787 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007788 VisibleTypeConversionsQuals.hasVolatile(),
7789 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007790 }
7791 }
7792
7793 // C++ [over.built]p5:
7794 //
7795 // For every pair (T, VQ), where T is a cv-qualified or
7796 // cv-unqualified object type, and VQ is either volatile or
7797 // empty, there exist candidate operator functions of the form
7798 //
7799 // T*VQ& operator++(T*VQ&);
7800 // T*VQ& operator--(T*VQ&);
7801 // T* operator++(T*VQ&, int);
7802 // T* operator--(T*VQ&, int);
7803 void addPlusPlusMinusMinusPointerOverloads() {
7804 for (BuiltinCandidateTypeSet::iterator
7805 Ptr = CandidateTypes[0].pointer_begin(),
7806 PtrEnd = CandidateTypes[0].pointer_end();
7807 Ptr != PtrEnd; ++Ptr) {
7808 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007809 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007810 continue;
7811
7812 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007813 (!(*Ptr).isVolatileQualified() &&
7814 VisibleTypeConversionsQuals.hasVolatile()),
7815 (!(*Ptr).isRestrictQualified() &&
7816 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007817 }
7818 }
7819
7820 // C++ [over.built]p6:
7821 // For every cv-qualified or cv-unqualified object type T, there
7822 // exist candidate operator functions of the form
7823 //
7824 // T& operator*(T*);
7825 //
7826 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007827 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007828 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007829 // T& operator*(T*);
7830 void addUnaryStarPointerOverloads() {
7831 for (BuiltinCandidateTypeSet::iterator
7832 Ptr = CandidateTypes[0].pointer_begin(),
7833 PtrEnd = CandidateTypes[0].pointer_end();
7834 Ptr != PtrEnd; ++Ptr) {
7835 QualType ParamTy = *Ptr;
7836 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007837 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7838 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007839
Douglas Gregor02824322011-01-26 19:30:28 +00007840 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7841 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7842 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007843
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007844 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007845 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007846 }
7847 }
7848
7849 // C++ [over.built]p9:
7850 // For every promoted arithmetic type T, there exist candidate
7851 // operator functions of the form
7852 //
7853 // T operator+(T);
7854 // T operator-(T);
7855 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007856 if (!HasArithmeticOrEnumeralCandidateType)
7857 return;
7858
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007859 for (unsigned Arith = FirstPromotedArithmeticType;
7860 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007861 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007862 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007863 }
7864
7865 // Extension: We also add these operators for vector types.
7866 for (BuiltinCandidateTypeSet::iterator
7867 Vec = CandidateTypes[0].vector_begin(),
7868 VecEnd = CandidateTypes[0].vector_end();
7869 Vec != VecEnd; ++Vec) {
7870 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007871 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007872 }
7873 }
7874
7875 // C++ [over.built]p8:
7876 // For every type T, there exist candidate operator functions of
7877 // the form
7878 //
7879 // T* operator+(T*);
7880 void addUnaryPlusPointerOverloads() {
7881 for (BuiltinCandidateTypeSet::iterator
7882 Ptr = CandidateTypes[0].pointer_begin(),
7883 PtrEnd = CandidateTypes[0].pointer_end();
7884 Ptr != PtrEnd; ++Ptr) {
7885 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007886 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007887 }
7888 }
7889
7890 // C++ [over.built]p10:
7891 // For every promoted integral type T, there exist candidate
7892 // operator functions of the form
7893 //
7894 // T operator~(T);
7895 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007896 if (!HasArithmeticOrEnumeralCandidateType)
7897 return;
7898
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007899 for (unsigned Int = FirstPromotedIntegralType;
7900 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007901 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007902 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007903 }
7904
7905 // Extension: We also add this operator for vector types.
7906 for (BuiltinCandidateTypeSet::iterator
7907 Vec = CandidateTypes[0].vector_begin(),
7908 VecEnd = CandidateTypes[0].vector_end();
7909 Vec != VecEnd; ++Vec) {
7910 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007911 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007912 }
7913 }
7914
7915 // C++ [over.match.oper]p16:
Richard Smith5e9746f2016-10-21 22:00:42 +00007916 // For every pointer to member type T or type std::nullptr_t, there
7917 // exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007918 //
7919 // bool operator==(T,T);
7920 // bool operator!=(T,T);
Richard Smith5e9746f2016-10-21 22:00:42 +00007921 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007922 /// Set of (canonical) types that we've already handled.
7923 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7924
Richard Smithe54c3072013-05-05 15:51:06 +00007925 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007926 for (BuiltinCandidateTypeSet::iterator
7927 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7928 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7929 MemPtr != MemPtrEnd;
7930 ++MemPtr) {
7931 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007932 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007933 continue;
7934
7935 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007936 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007937 }
Richard Smith5e9746f2016-10-21 22:00:42 +00007938
7939 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7940 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7941 if (AddedTypes.insert(NullPtrTy).second) {
7942 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7943 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7944 CandidateSet);
7945 }
7946 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007947 }
7948 }
7949
7950 // C++ [over.built]p15:
7951 //
Richard Smith5e9746f2016-10-21 22:00:42 +00007952 // For every T, where T is an enumeration type or a pointer type,
7953 // there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007954 //
7955 // bool operator<(T, T);
7956 // bool operator>(T, T);
7957 // bool operator<=(T, T);
7958 // bool operator>=(T, T);
7959 // bool operator==(T, T);
7960 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007961 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007962 // C++ [over.match.oper]p3:
7963 // [...]the built-in candidates include all of the candidate operator
7964 // functions defined in 13.6 that, compared to the given operator, [...]
7965 // do not have the same parameter-type-list as any non-template non-member
7966 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007967 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007968 // Note that in practice, this only affects enumeration types because there
7969 // aren't any built-in candidates of record type, and a user-defined operator
7970 // must have an operand of record or enumeration type. Also, the only other
7971 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007972 // cannot be overloaded for enumeration types, so this is the only place
7973 // where we must suppress candidates like this.
7974 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7975 UserDefinedBinaryOperators;
7976
Richard Smithe54c3072013-05-05 15:51:06 +00007977 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007978 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7979 CandidateTypes[ArgIdx].enumeration_end()) {
7980 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7981 CEnd = CandidateSet.end();
7982 C != CEnd; ++C) {
7983 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7984 continue;
7985
Eli Friedman14f082b2012-09-18 21:52:24 +00007986 if (C->Function->isFunctionTemplateSpecialization())
7987 continue;
7988
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007989 QualType FirstParamType =
7990 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7991 QualType SecondParamType =
7992 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7993
7994 // Skip if either parameter isn't of enumeral type.
7995 if (!FirstParamType->isEnumeralType() ||
7996 !SecondParamType->isEnumeralType())
7997 continue;
7998
7999 // Add this operator to the set of known user-defined operators.
8000 UserDefinedBinaryOperators.insert(
8001 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8002 S.Context.getCanonicalType(SecondParamType)));
8003 }
8004 }
8005 }
8006
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008007 /// Set of (canonical) types that we've already handled.
8008 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8009
Richard Smithe54c3072013-05-05 15:51:06 +00008010 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008011 for (BuiltinCandidateTypeSet::iterator
8012 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8013 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8014 Ptr != PtrEnd; ++Ptr) {
8015 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008016 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008017 continue;
8018
8019 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008020 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008021 }
8022 for (BuiltinCandidateTypeSet::iterator
8023 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8024 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8025 Enum != EnumEnd; ++Enum) {
8026 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8027
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008028 // Don't add the same builtin candidate twice, or if a user defined
8029 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00008030 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008031 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8032 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008033 continue;
8034
8035 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008036 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008037 }
8038 }
8039 }
8040
8041 // C++ [over.built]p13:
8042 //
8043 // For every cv-qualified or cv-unqualified object type T
8044 // there exist candidate operator functions of the form
8045 //
8046 // T* operator+(T*, ptrdiff_t);
8047 // T& operator[](T*, ptrdiff_t); [BELOW]
8048 // T* operator-(T*, ptrdiff_t);
8049 // T* operator+(ptrdiff_t, T*);
8050 // T& operator[](ptrdiff_t, T*); [BELOW]
8051 //
8052 // C++ [over.built]p14:
8053 //
8054 // For every T, where T is a pointer to object type, there
8055 // exist candidate operator functions of the form
8056 //
8057 // ptrdiff_t operator-(T, T);
8058 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8059 /// Set of (canonical) types that we've already handled.
8060 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8061
8062 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00008063 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008064 S.Context.getPointerDiffType(),
8065 S.Context.getPointerDiffType(),
8066 };
8067 for (BuiltinCandidateTypeSet::iterator
8068 Ptr = CandidateTypes[Arg].pointer_begin(),
8069 PtrEnd = CandidateTypes[Arg].pointer_end();
8070 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00008071 QualType PointeeTy = (*Ptr)->getPointeeType();
8072 if (!PointeeTy->isObjectType())
8073 continue;
8074
Eric Christopher9207a522015-08-21 16:24:01 +00008075 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008076 if (Arg == 0 || Op == OO_Plus) {
8077 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8078 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00008079 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008080 }
8081 if (Op == OO_Minus) {
8082 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00008083 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008084 continue;
8085
8086 QualType ParamTypes[2] = { *Ptr, *Ptr };
8087 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00008088 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008089 }
8090 }
8091 }
8092 }
8093
8094 // C++ [over.built]p12:
8095 //
8096 // For every pair of promoted arithmetic types L and R, there
8097 // exist candidate operator functions of the form
8098 //
8099 // LR operator*(L, R);
8100 // LR operator/(L, R);
8101 // LR operator+(L, R);
8102 // LR operator-(L, R);
8103 // bool operator<(L, R);
8104 // bool operator>(L, R);
8105 // bool operator<=(L, R);
8106 // bool operator>=(L, R);
8107 // bool operator==(L, R);
8108 // bool operator!=(L, R);
8109 //
8110 // where LR is the result of the usual arithmetic conversions
8111 // between types L and R.
8112 //
8113 // C++ [over.built]p24:
8114 //
8115 // For every pair of promoted arithmetic types L and R, there exist
8116 // candidate operator functions of the form
8117 //
8118 // LR operator?(bool, L, R);
8119 //
8120 // where LR is the result of the usual arithmetic conversions
8121 // between types L and R.
8122 // Our candidates ignore the first parameter.
8123 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008124 if (!HasArithmeticOrEnumeralCandidateType)
8125 return;
8126
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008127 for (unsigned Left = FirstPromotedArithmeticType;
8128 Left < LastPromotedArithmeticType; ++Left) {
8129 for (unsigned Right = FirstPromotedArithmeticType;
8130 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00008131 QualType LandR[2] = { getArithmeticType(Left),
8132 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008133 QualType Result =
8134 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00008135 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00008136 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008137 }
8138 }
8139
8140 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8141 // conditional operator for vector types.
8142 for (BuiltinCandidateTypeSet::iterator
8143 Vec1 = CandidateTypes[0].vector_begin(),
8144 Vec1End = CandidateTypes[0].vector_end();
8145 Vec1 != Vec1End; ++Vec1) {
8146 for (BuiltinCandidateTypeSet::iterator
8147 Vec2 = CandidateTypes[1].vector_begin(),
8148 Vec2End = CandidateTypes[1].vector_end();
8149 Vec2 != Vec2End; ++Vec2) {
8150 QualType LandR[2] = { *Vec1, *Vec2 };
8151 QualType Result = S.Context.BoolTy;
8152 if (!isComparison) {
8153 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
8154 Result = *Vec1;
8155 else
8156 Result = *Vec2;
8157 }
8158
Richard Smithe54c3072013-05-05 15:51:06 +00008159 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008160 }
8161 }
8162 }
8163
8164 // C++ [over.built]p17:
8165 //
8166 // For every pair of promoted integral types L and R, there
8167 // exist candidate operator functions of the form
8168 //
8169 // LR operator%(L, R);
8170 // LR operator&(L, R);
8171 // LR operator^(L, R);
8172 // LR operator|(L, R);
8173 // L operator<<(L, R);
8174 // L operator>>(L, R);
8175 //
8176 // where LR is the result of the usual arithmetic conversions
8177 // between types L and R.
8178 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008179 if (!HasArithmeticOrEnumeralCandidateType)
8180 return;
8181
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008182 for (unsigned Left = FirstPromotedIntegralType;
8183 Left < LastPromotedIntegralType; ++Left) {
8184 for (unsigned Right = FirstPromotedIntegralType;
8185 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00008186 QualType LandR[2] = { getArithmeticType(Left),
8187 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008188 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
8189 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00008190 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00008191 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008192 }
8193 }
8194 }
8195
8196 // C++ [over.built]p20:
8197 //
8198 // For every pair (T, VQ), where T is an enumeration or
8199 // pointer to member type and VQ is either volatile or
8200 // empty, there exist candidate operator functions of the form
8201 //
8202 // VQ T& operator=(VQ T&, T);
8203 void addAssignmentMemberPointerOrEnumeralOverloads() {
8204 /// Set of (canonical) types that we've already handled.
8205 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8206
8207 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8208 for (BuiltinCandidateTypeSet::iterator
8209 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8210 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8211 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00008212 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008213 continue;
8214
Richard Smithe54c3072013-05-05 15:51:06 +00008215 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008216 }
8217
8218 for (BuiltinCandidateTypeSet::iterator
8219 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8220 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8221 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008222 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008223 continue;
8224
Richard Smithe54c3072013-05-05 15:51:06 +00008225 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008226 }
8227 }
8228 }
8229
8230 // C++ [over.built]p19:
8231 //
8232 // For every pair (T, VQ), where T is any type and VQ is either
8233 // volatile or empty, there exist candidate operator functions
8234 // of the form
8235 //
8236 // T*VQ& operator=(T*VQ&, T*);
8237 //
8238 // C++ [over.built]p21:
8239 //
8240 // For every pair (T, VQ), where T is a cv-qualified or
8241 // cv-unqualified object type and VQ is either volatile or
8242 // empty, there exist candidate operator functions of the form
8243 //
8244 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8245 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8246 void addAssignmentPointerOverloads(bool isEqualOp) {
8247 /// Set of (canonical) types that we've already handled.
8248 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8249
8250 for (BuiltinCandidateTypeSet::iterator
8251 Ptr = CandidateTypes[0].pointer_begin(),
8252 PtrEnd = CandidateTypes[0].pointer_end();
8253 Ptr != PtrEnd; ++Ptr) {
8254 // If this is operator=, keep track of the builtin candidates we added.
8255 if (isEqualOp)
8256 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00008257 else if (!(*Ptr)->getPointeeType()->isObjectType())
8258 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008259
8260 // non-volatile version
8261 QualType ParamTypes[2] = {
8262 S.Context.getLValueReferenceType(*Ptr),
8263 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8264 };
Richard Smithe54c3072013-05-05 15:51:06 +00008265 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008266 /*IsAssigmentOperator=*/ isEqualOp);
8267
Douglas Gregor5bee2582012-06-04 00:15:09 +00008268 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8269 VisibleTypeConversionsQuals.hasVolatile();
8270 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008271 // volatile version
8272 ParamTypes[0] =
8273 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008274 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008275 /*IsAssigmentOperator=*/isEqualOp);
8276 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008277
8278 if (!(*Ptr).isRestrictQualified() &&
8279 VisibleTypeConversionsQuals.hasRestrict()) {
8280 // restrict version
8281 ParamTypes[0]
8282 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008283 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008284 /*IsAssigmentOperator=*/isEqualOp);
8285
8286 if (NeedVolatile) {
8287 // volatile restrict version
8288 ParamTypes[0]
8289 = S.Context.getLValueReferenceType(
8290 S.Context.getCVRQualifiedType(*Ptr,
8291 (Qualifiers::Volatile |
8292 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008293 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00008294 /*IsAssigmentOperator=*/isEqualOp);
8295 }
8296 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008297 }
8298
8299 if (isEqualOp) {
8300 for (BuiltinCandidateTypeSet::iterator
8301 Ptr = CandidateTypes[1].pointer_begin(),
8302 PtrEnd = CandidateTypes[1].pointer_end();
8303 Ptr != PtrEnd; ++Ptr) {
8304 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00008305 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008306 continue;
8307
Chandler Carruth8e543b32010-12-12 08:17:55 +00008308 QualType ParamTypes[2] = {
8309 S.Context.getLValueReferenceType(*Ptr),
8310 *Ptr,
8311 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008312
8313 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00008314 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008315 /*IsAssigmentOperator=*/true);
8316
Douglas Gregor5bee2582012-06-04 00:15:09 +00008317 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8318 VisibleTypeConversionsQuals.hasVolatile();
8319 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008320 // volatile version
8321 ParamTypes[0] =
8322 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008323 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8324 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008325 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00008326
8327 if (!(*Ptr).isRestrictQualified() &&
8328 VisibleTypeConversionsQuals.hasRestrict()) {
8329 // restrict version
8330 ParamTypes[0]
8331 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00008332 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8333 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008334
8335 if (NeedVolatile) {
8336 // volatile restrict version
8337 ParamTypes[0]
8338 = S.Context.getLValueReferenceType(
8339 S.Context.getCVRQualifiedType(*Ptr,
8340 (Qualifiers::Volatile |
8341 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008342 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8343 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008344 }
8345 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008346 }
8347 }
8348 }
8349
8350 // C++ [over.built]p18:
8351 //
8352 // For every triple (L, VQ, R), where L is an arithmetic type,
8353 // VQ is either volatile or empty, and R is a promoted
8354 // arithmetic type, there exist candidate operator functions of
8355 // the form
8356 //
8357 // VQ L& operator=(VQ L&, R);
8358 // VQ L& operator*=(VQ L&, R);
8359 // VQ L& operator/=(VQ L&, R);
8360 // VQ L& operator+=(VQ L&, R);
8361 // VQ L& operator-=(VQ L&, R);
8362 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008363 if (!HasArithmeticOrEnumeralCandidateType)
8364 return;
8365
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008366 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8367 for (unsigned Right = FirstPromotedArithmeticType;
8368 Right < LastPromotedArithmeticType; ++Right) {
8369 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008370 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008371
8372 // Add this built-in operator as a candidate (VQ is empty).
8373 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008374 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008375 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008376 /*IsAssigmentOperator=*/isEqualOp);
8377
8378 // Add this built-in operator as a candidate (VQ is 'volatile').
8379 if (VisibleTypeConversionsQuals.hasVolatile()) {
8380 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008381 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008382 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008383 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008384 /*IsAssigmentOperator=*/isEqualOp);
8385 }
8386 }
8387 }
8388
8389 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8390 for (BuiltinCandidateTypeSet::iterator
8391 Vec1 = CandidateTypes[0].vector_begin(),
8392 Vec1End = CandidateTypes[0].vector_end();
8393 Vec1 != Vec1End; ++Vec1) {
8394 for (BuiltinCandidateTypeSet::iterator
8395 Vec2 = CandidateTypes[1].vector_begin(),
8396 Vec2End = CandidateTypes[1].vector_end();
8397 Vec2 != Vec2End; ++Vec2) {
8398 QualType ParamTypes[2];
8399 ParamTypes[1] = *Vec2;
8400 // Add this built-in operator as a candidate (VQ is empty).
8401 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008402 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008403 /*IsAssigmentOperator=*/isEqualOp);
8404
8405 // Add this built-in operator as a candidate (VQ is 'volatile').
8406 if (VisibleTypeConversionsQuals.hasVolatile()) {
8407 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8408 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008409 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008410 /*IsAssigmentOperator=*/isEqualOp);
8411 }
8412 }
8413 }
8414 }
8415
8416 // C++ [over.built]p22:
8417 //
8418 // For every triple (L, VQ, R), where L is an integral type, VQ
8419 // is either volatile or empty, and R is a promoted integral
8420 // type, there exist candidate operator functions of the form
8421 //
8422 // VQ L& operator%=(VQ L&, R);
8423 // VQ L& operator<<=(VQ L&, R);
8424 // VQ L& operator>>=(VQ L&, R);
8425 // VQ L& operator&=(VQ L&, R);
8426 // VQ L& operator^=(VQ L&, R);
8427 // VQ L& operator|=(VQ L&, R);
8428 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008429 if (!HasArithmeticOrEnumeralCandidateType)
8430 return;
8431
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008432 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8433 for (unsigned Right = FirstPromotedIntegralType;
8434 Right < LastPromotedIntegralType; ++Right) {
8435 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008436 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008437
8438 // Add this built-in operator as a candidate (VQ is empty).
8439 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008440 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008441 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008442 if (VisibleTypeConversionsQuals.hasVolatile()) {
8443 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008444 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008445 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8446 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008447 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008448 }
8449 }
8450 }
8451 }
8452
8453 // C++ [over.operator]p23:
8454 //
8455 // There also exist candidate operator functions of the form
8456 //
8457 // bool operator!(bool);
8458 // bool operator&&(bool, bool);
8459 // bool operator||(bool, bool);
8460 void addExclaimOverload() {
8461 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008462 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008463 /*IsAssignmentOperator=*/false,
8464 /*NumContextualBoolArguments=*/1);
8465 }
8466 void addAmpAmpOrPipePipeOverload() {
8467 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008468 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008469 /*IsAssignmentOperator=*/false,
8470 /*NumContextualBoolArguments=*/2);
8471 }
8472
8473 // C++ [over.built]p13:
8474 //
8475 // For every cv-qualified or cv-unqualified object type T there
8476 // exist candidate operator functions of the form
8477 //
8478 // T* operator+(T*, ptrdiff_t); [ABOVE]
8479 // T& operator[](T*, ptrdiff_t);
8480 // T* operator-(T*, ptrdiff_t); [ABOVE]
8481 // T* operator+(ptrdiff_t, T*); [ABOVE]
8482 // T& operator[](ptrdiff_t, T*);
8483 void addSubscriptOverloads() {
8484 for (BuiltinCandidateTypeSet::iterator
8485 Ptr = CandidateTypes[0].pointer_begin(),
8486 PtrEnd = CandidateTypes[0].pointer_end();
8487 Ptr != PtrEnd; ++Ptr) {
8488 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8489 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008490 if (!PointeeType->isObjectType())
8491 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008492
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008493 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8494
8495 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008496 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008497 }
8498
8499 for (BuiltinCandidateTypeSet::iterator
8500 Ptr = CandidateTypes[1].pointer_begin(),
8501 PtrEnd = CandidateTypes[1].pointer_end();
8502 Ptr != PtrEnd; ++Ptr) {
8503 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8504 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008505 if (!PointeeType->isObjectType())
8506 continue;
8507
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008508 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8509
8510 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008511 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008512 }
8513 }
8514
8515 // C++ [over.built]p11:
8516 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8517 // C1 is the same type as C2 or is a derived class of C2, T is an object
8518 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8519 // there exist candidate operator functions of the form
8520 //
8521 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8522 //
8523 // where CV12 is the union of CV1 and CV2.
8524 void addArrowStarOverloads() {
8525 for (BuiltinCandidateTypeSet::iterator
8526 Ptr = CandidateTypes[0].pointer_begin(),
8527 PtrEnd = CandidateTypes[0].pointer_end();
8528 Ptr != PtrEnd; ++Ptr) {
8529 QualType C1Ty = (*Ptr);
8530 QualType C1;
8531 QualifierCollector Q1;
8532 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8533 if (!isa<RecordType>(C1))
8534 continue;
8535 // heuristic to reduce number of builtin candidates in the set.
8536 // Add volatile/restrict version only if there are conversions to a
8537 // volatile/restrict type.
8538 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8539 continue;
8540 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8541 continue;
8542 for (BuiltinCandidateTypeSet::iterator
8543 MemPtr = CandidateTypes[1].member_pointer_begin(),
8544 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8545 MemPtr != MemPtrEnd; ++MemPtr) {
8546 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8547 QualType C2 = QualType(mptr->getClass(), 0);
8548 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008549 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008550 break;
8551 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8552 // build CV12 T&
8553 QualType T = mptr->getPointeeType();
8554 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8555 T.isVolatileQualified())
8556 continue;
8557 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8558 T.isRestrictQualified())
8559 continue;
8560 T = Q1.apply(S.Context, T);
8561 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008562 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008563 }
8564 }
8565 }
8566
8567 // Note that we don't consider the first argument, since it has been
8568 // contextually converted to bool long ago. The candidates below are
8569 // therefore added as binary.
8570 //
8571 // C++ [over.built]p25:
8572 // For every type T, where T is a pointer, pointer-to-member, or scoped
8573 // enumeration type, there exist candidate operator functions of the form
8574 //
8575 // T operator?(bool, T, T);
8576 //
8577 void addConditionalOperatorOverloads() {
8578 /// Set of (canonical) types that we've already handled.
8579 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8580
8581 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8582 for (BuiltinCandidateTypeSet::iterator
8583 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8584 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8585 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008586 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008587 continue;
8588
8589 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008590 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008591 }
8592
8593 for (BuiltinCandidateTypeSet::iterator
8594 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8595 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8596 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008597 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008598 continue;
8599
8600 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008601 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008602 }
8603
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008604 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008605 for (BuiltinCandidateTypeSet::iterator
8606 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8607 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8608 Enum != EnumEnd; ++Enum) {
8609 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8610 continue;
8611
David Blaikie82e95a32014-11-19 07:49:47 +00008612 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008613 continue;
8614
8615 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008616 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008617 }
8618 }
8619 }
8620 }
8621};
8622
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008623} // end anonymous namespace
8624
8625/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8626/// operator overloads to the candidate set (C++ [over.built]), based
8627/// on the operator @p Op and the arguments given. For example, if the
8628/// operator is a binary '+', this routine might add "int
8629/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008630void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8631 SourceLocation OpLoc,
8632 ArrayRef<Expr *> Args,
8633 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008634 // Find all of the types that the arguments can convert to, but only
8635 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008636 // that make use of these types. Also record whether we encounter non-record
8637 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008638 Qualifiers VisibleTypeConversionsQuals;
8639 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008640 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008641 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008642
8643 bool HasNonRecordCandidateType = false;
8644 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008645 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008646 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008647 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008648 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8649 OpLoc,
8650 true,
8651 (Op == OO_Exclaim ||
8652 Op == OO_AmpAmp ||
8653 Op == OO_PipePipe),
8654 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008655 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8656 CandidateTypes[ArgIdx].hasNonRecordTypes();
8657 HasArithmeticOrEnumeralCandidateType =
8658 HasArithmeticOrEnumeralCandidateType ||
8659 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008660 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008661
Chandler Carruth00a38332010-12-13 01:44:01 +00008662 // Exit early when no non-record types have been added to the candidate set
8663 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008664 //
8665 // We can't exit early for !, ||, or &&, since there we have always have
8666 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008667 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008668 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008669 return;
8670
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008671 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008672 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008673 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008674 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008675 CandidateTypes, CandidateSet);
8676
8677 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008678 switch (Op) {
8679 case OO_None:
8680 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008681 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008682
Chandler Carruth5184de02010-12-12 08:51:33 +00008683 case OO_New:
8684 case OO_Delete:
8685 case OO_Array_New:
8686 case OO_Array_Delete:
8687 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008688 llvm_unreachable(
8689 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008690
8691 case OO_Comma:
8692 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008693 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008694 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008695 // -- For the operator ',', the unary operator '&', the
8696 // operator '->', or the operator 'co_await', the
8697 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008698 break;
8699
8700 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008701 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008702 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008703 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008704
8705 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008706 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008707 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008708 } else {
8709 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8710 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8711 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008712 break;
8713
Chandler Carruth5184de02010-12-12 08:51:33 +00008714 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008715 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008716 OpBuilder.addUnaryStarPointerOverloads();
8717 else
8718 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8719 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008720
Chandler Carruth5184de02010-12-12 08:51:33 +00008721 case OO_Slash:
8722 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008723 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008724
8725 case OO_PlusPlus:
8726 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008727 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8728 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008729 break;
8730
Douglas Gregor84605ae2009-08-24 13:43:27 +00008731 case OO_EqualEqual:
8732 case OO_ExclaimEqual:
Richard Smith5e9746f2016-10-21 22:00:42 +00008733 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008734 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008735
Douglas Gregora11693b2008-11-12 17:17:38 +00008736 case OO_Less:
8737 case OO_Greater:
8738 case OO_LessEqual:
8739 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008740 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008741 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8742 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008743
Douglas Gregora11693b2008-11-12 17:17:38 +00008744 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008745 case OO_Caret:
8746 case OO_Pipe:
8747 case OO_LessLess:
8748 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008749 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008750 break;
8751
Chandler Carruth5184de02010-12-12 08:51:33 +00008752 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008753 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008754 // C++ [over.match.oper]p3:
8755 // -- For the operator ',', the unary operator '&', or the
8756 // operator '->', the built-in candidates set is empty.
8757 break;
8758
8759 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8760 break;
8761
8762 case OO_Tilde:
8763 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8764 break;
8765
Douglas Gregora11693b2008-11-12 17:17:38 +00008766 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008767 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008768 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008769
8770 case OO_PlusEqual:
8771 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008772 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008773 // Fall through.
8774
8775 case OO_StarEqual:
8776 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008777 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008778 break;
8779
8780 case OO_PercentEqual:
8781 case OO_LessLessEqual:
8782 case OO_GreaterGreaterEqual:
8783 case OO_AmpEqual:
8784 case OO_CaretEqual:
8785 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008786 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008787 break;
8788
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008789 case OO_Exclaim:
8790 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008791 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008792
Douglas Gregora11693b2008-11-12 17:17:38 +00008793 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008794 case OO_PipePipe:
8795 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008796 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008797
8798 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008799 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008800 break;
8801
8802 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008803 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008804 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008805
8806 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008807 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008808 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8809 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008810 }
8811}
8812
Douglas Gregore254f902009-02-04 00:32:51 +00008813/// \brief Add function candidates found via argument-dependent lookup
8814/// to the set of overloading candidates.
8815///
8816/// This routine performs argument-dependent name lookup based on the
8817/// given function name (which may also be an operator name) and adds
8818/// all of the overload candidates found by ADL to the overload
8819/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008820void
Douglas Gregore254f902009-02-04 00:32:51 +00008821Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008822 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008823 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008824 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008825 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008826 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008827 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008828
John McCall91f61fc2010-01-26 06:04:06 +00008829 // FIXME: This approach for uniquing ADL results (and removing
8830 // redundant candidates from the set) relies on pointer-equality,
8831 // which means we need to key off the canonical decl. However,
8832 // always going back to the canonical decl might not get us the
8833 // right set of default arguments. What default arguments are
8834 // we supposed to consider on ADL candidates, anyway?
8835
Douglas Gregorcabea402009-09-22 15:41:20 +00008836 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008837 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008838
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008839 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008840 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8841 CandEnd = CandidateSet.end();
8842 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008843 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008844 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008845 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008846 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008847 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008848
8849 // For each of the ADL candidates we found, add it to the overload
8850 // set.
John McCall8fe68082010-01-26 07:16:45 +00008851 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008852 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008853 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008854 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008855 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008856
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008857 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8858 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008859 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008860 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008861 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008862 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008863 }
Douglas Gregore254f902009-02-04 00:32:51 +00008864}
8865
George Burgess IV3dc166912016-05-10 01:59:34 +00008866namespace {
8867enum class Comparison { Equal, Better, Worse };
8868}
8869
8870/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8871/// overload resolution.
8872///
8873/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8874/// Cand1's first N enable_if attributes have precisely the same conditions as
8875/// Cand2's first N enable_if attributes (where N = the number of enable_if
8876/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8877///
8878/// Note that you can have a pair of candidates such that Cand1's enable_if
8879/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8880/// worse than Cand1's.
8881static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8882 const FunctionDecl *Cand2) {
8883 // Common case: One (or both) decls don't have enable_if attrs.
8884 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8885 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8886 if (!Cand1Attr || !Cand2Attr) {
8887 if (Cand1Attr == Cand2Attr)
8888 return Comparison::Equal;
8889 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8890 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008891
8892 // FIXME: The next several lines are just
8893 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8894 // instead of reverse order which is how they're stored in the AST.
8895 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8896 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8897
George Burgess IV3dc166912016-05-10 01:59:34 +00008898 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8899 // has fewer enable_if attributes than Cand2.
8900 if (Cand1Attrs.size() < Cand2Attrs.size())
8901 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008902
8903 auto Cand1I = Cand1Attrs.begin();
8904 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8905 for (auto &Cand2A : Cand2Attrs) {
8906 Cand1ID.clear();
8907 Cand2ID.clear();
8908
8909 auto &Cand1A = *Cand1I++;
8910 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8911 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8912 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008913 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008914 }
8915
George Burgess IV3dc166912016-05-10 01:59:34 +00008916 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008917}
8918
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008919/// isBetterOverloadCandidate - Determines whether the first overload
8920/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008921bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8922 const OverloadCandidate &Cand2,
8923 SourceLocation Loc,
8924 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008925 // Define viable functions to be better candidates than non-viable
8926 // functions.
8927 if (!Cand2.Viable)
8928 return Cand1.Viable;
8929 else if (!Cand1.Viable)
8930 return false;
8931
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008932 // C++ [over.match.best]p1:
8933 //
8934 // -- if F is a static member function, ICS1(F) is defined such
8935 // that ICS1(F) is neither better nor worse than ICS1(G) for
8936 // any function G, and, symmetrically, ICS1(G) is neither
8937 // better nor worse than ICS1(F).
8938 unsigned StartArg = 0;
8939 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8940 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008941
George Burgess IVfbad5b22016-09-07 20:03:19 +00008942 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8943 // We don't allow incompatible pointer conversions in C++.
8944 if (!S.getLangOpts().CPlusPlus)
8945 return ICS.isStandard() &&
8946 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8947
8948 // The only ill-formed conversion we allow in C++ is the string literal to
8949 // char* conversion, which is only considered ill-formed after C++11.
8950 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8951 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8952 };
8953
8954 // Define functions that don't require ill-formed conversions for a given
8955 // argument to be better candidates than functions that do.
Richard Smith6eedfe72017-01-09 08:01:21 +00008956 unsigned NumArgs = Cand1.Conversions.size();
8957 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
George Burgess IVfbad5b22016-09-07 20:03:19 +00008958 bool HasBetterConversion = false;
8959 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8960 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8961 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8962 if (Cand1Bad != Cand2Bad) {
8963 if (Cand1Bad)
8964 return false;
8965 HasBetterConversion = true;
8966 }
8967 }
8968
8969 if (HasBetterConversion)
8970 return true;
8971
Douglas Gregord3cb3562009-07-07 23:38:56 +00008972 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008973 // A viable function F1 is defined to be a better function than another
8974 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008975 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008976 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008977 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008978 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008979 Cand2.Conversions[ArgIdx])) {
8980 case ImplicitConversionSequence::Better:
8981 // Cand1 has a better conversion sequence.
8982 HasBetterConversion = true;
8983 break;
8984
8985 case ImplicitConversionSequence::Worse:
8986 // Cand1 can't be better than Cand2.
8987 return false;
8988
8989 case ImplicitConversionSequence::Indistinguishable:
8990 // Do nothing.
8991 break;
8992 }
8993 }
8994
Mike Stump11289f42009-09-09 15:08:12 +00008995 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008996 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008997 if (HasBetterConversion)
8998 return true;
8999
Douglas Gregora1f013e2008-11-07 22:36:19 +00009000 // -- the context is an initialization by user-defined conversion
9001 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9002 // from the return type of F1 to the destination type (i.e.,
9003 // the type of the entity being initialized) is a better
9004 // conversion sequence than the standard conversion sequence
9005 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00009006 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00009007 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00009008 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00009009 // First check whether we prefer one of the conversion functions over the
9010 // other. This only distinguishes the results in non-standard, extension
9011 // cases such as the conversion from a lambda closure type to a function
9012 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00009013 ImplicitConversionSequence::CompareKind Result =
9014 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9015 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00009016 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00009017 Cand1.FinalConversion,
9018 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00009019
Richard Smithec2748a2014-05-17 04:36:39 +00009020 if (Result != ImplicitConversionSequence::Indistinguishable)
9021 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00009022
9023 // FIXME: Compare kind of reference binding if conversion functions
9024 // convert to a reference type used in direct reference binding, per
9025 // C++14 [over.match.best]p1 section 2 bullet 3.
9026 }
9027
Richard Smith32918772017-02-14 00:25:28 +00009028 // -- F1 is generated from a deduction-guide and F2 is not
Richard Smithbc491202017-02-17 20:05:37 +00009029 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9030 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9031 if (Guide1 && Guide2 && Guide1->isImplicit() != Guide2->isImplicit())
9032 return Guide2->isImplicit();
Richard Smith32918772017-02-14 00:25:28 +00009033
Richard Smith6fdeaab2014-05-17 01:58:45 +00009034 // -- F1 is a non-template function and F2 is a function template
9035 // specialization, or, if not that,
9036 bool Cand1IsSpecialization = Cand1.Function &&
9037 Cand1.Function->getPrimaryTemplate();
9038 bool Cand2IsSpecialization = Cand2.Function &&
9039 Cand2.Function->getPrimaryTemplate();
9040 if (Cand1IsSpecialization != Cand2IsSpecialization)
9041 return Cand2IsSpecialization;
9042
9043 // -- F1 and F2 are function template specializations, and the function
9044 // template for F1 is more specialized than the template for F2
9045 // according to the partial ordering rules described in 14.5.5.2, or,
9046 // if not that,
9047 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9048 if (FunctionTemplateDecl *BetterTemplate
9049 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9050 Cand2.Function->getPrimaryTemplate(),
9051 Loc,
9052 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9053 : TPOC_Call,
9054 Cand1.ExplicitCallArguments,
9055 Cand2.ExplicitCallArguments))
9056 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00009057 }
9058
Richard Smith5179eb72016-06-28 19:03:57 +00009059 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9060 // A derived-class constructor beats an (inherited) base class constructor.
9061 bool Cand1IsInherited =
9062 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9063 bool Cand2IsInherited =
9064 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9065 if (Cand1IsInherited != Cand2IsInherited)
9066 return Cand2IsInherited;
9067 else if (Cand1IsInherited) {
9068 assert(Cand2IsInherited);
9069 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9070 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9071 if (Cand1Class->isDerivedFrom(Cand2Class))
9072 return true;
9073 if (Cand2Class->isDerivedFrom(Cand1Class))
9074 return false;
9075 // Inherited from sibling base classes: still ambiguous.
9076 }
9077
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009078 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00009079 if (Cand1.Function && Cand2.Function) {
9080 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9081 if (Cmp != Comparison::Equal)
9082 return Cmp == Comparison::Better;
9083 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009084
Justin Lebar25c4a812016-03-29 16:24:16 +00009085 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00009086 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9087 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9088 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9089 }
9090
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009091 bool HasPS1 = Cand1.Function != nullptr &&
9092 functionHasPassObjectSizeParams(Cand1.Function);
9093 bool HasPS2 = Cand2.Function != nullptr &&
9094 functionHasPassObjectSizeParams(Cand2.Function);
9095 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009096}
9097
Richard Smith2dbe4042015-11-04 19:26:32 +00009098/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00009099/// name lookup and overload resolution. This applies when the same internal/no
9100/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00009101/// the same header). In such a case, we don't consider the declarations to
9102/// declare the same entity, but we also don't want lookups with both
9103/// declarations visible to be ambiguous in some cases (this happens when using
9104/// a modularized libstdc++).
9105bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9106 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00009107 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9108 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9109 if (!VA || !VB)
9110 return false;
9111
9112 // The declarations must be declaring the same name as an internal linkage
9113 // entity in different modules.
9114 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9115 VB->getDeclContext()->getRedeclContext()) ||
9116 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9117 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9118 VA->isExternallyVisible() || VB->isExternallyVisible())
9119 return false;
9120
9121 // Check that the declarations appear to be equivalent.
9122 //
9123 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9124 // For constants and functions, we should check the initializer or body is
9125 // the same. For non-constant variables, we shouldn't allow it at all.
9126 if (Context.hasSameType(VA->getType(), VB->getType()))
9127 return true;
9128
9129 // Enum constants within unnamed enumerations will have different types, but
9130 // may still be similar enough to be interchangeable for our purposes.
9131 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9132 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9133 // Only handle anonymous enums. If the enumerations were named and
9134 // equivalent, they would have been merged to the same type.
9135 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9136 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9137 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9138 !Context.hasSameType(EnumA->getIntegerType(),
9139 EnumB->getIntegerType()))
9140 return false;
9141 // Allow this only if the value is the same for both enumerators.
9142 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9143 }
9144 }
9145
9146 // Nothing else is sufficiently similar.
9147 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00009148}
9149
9150void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9151 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9152 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9153
9154 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9155 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9156 << !M << (M ? M->getFullModuleName() : "");
9157
9158 for (auto *E : Equiv) {
9159 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9160 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9161 << !M << (M ? M->getFullModuleName() : "");
9162 }
Richard Smith896c66e2015-10-21 07:13:52 +00009163}
9164
Mike Stump11289f42009-09-09 15:08:12 +00009165/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009166/// within an overload candidate set.
9167///
James Dennettffad8b72012-06-22 08:10:18 +00009168/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009169/// which overload resolution occurs.
9170///
James Dennettffad8b72012-06-22 08:10:18 +00009171/// \param Best If overload resolution was successful or found a deleted
9172/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009173///
9174/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00009175OverloadingResult
9176OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00009177 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00009178 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00009179 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9180 std::transform(begin(), end(), std::back_inserter(Candidates),
9181 [](OverloadCandidate &Cand) { return &Cand; });
9182
Justin Lebar66a2ab92016-08-10 00:40:43 +00009183 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9184 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00009185 // compilation mode only one call variant is viable. We need to
9186 // exclude non-viable overload candidates from consideration based
9187 // only on their host/device attributes. Specifically, if one
9188 // candidate call is WrongSide and the other is SameSide, we ignore
9189 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00009190 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00009191 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9192 bool ContainsSameSideCandidate =
9193 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9194 return Cand->Function &&
9195 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9196 Sema::CFP_SameSide;
9197 });
9198 if (ContainsSameSideCandidate) {
9199 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9200 return Cand->Function &&
9201 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9202 Sema::CFP_WrongSide;
9203 };
George Burgess IV8684b032017-01-04 19:16:29 +00009204 llvm::erase_if(Candidates, IsWrongSideCandidate);
Artem Belevich18609102016-02-12 18:29:18 +00009205 }
9206 }
9207
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009208 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00009209 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00009210 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00009211 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009212 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00009213 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009214 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009215
9216 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00009217 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009218 return OR_No_Viable_Function;
9219
Richard Smith2dbe4042015-11-04 19:26:32 +00009220 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00009221
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009222 // Make sure that this function is better than every other viable
9223 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00009224 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00009225 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009226 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009227 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00009228 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00009229 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9230 Cand->Function)) {
9231 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00009232 continue;
9233 }
9234
John McCall5c32be02010-08-24 20:38:10 +00009235 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009236 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00009237 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009238 }
Mike Stump11289f42009-09-09 15:08:12 +00009239
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009240 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00009241 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009242 (Best->Function->isDeleted() ||
George Burgess IVce6284b2017-01-28 02:19:40 +00009243 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00009244 return OR_Deleted;
9245
Richard Smith2dbe4042015-11-04 19:26:32 +00009246 if (!EquivalentCands.empty())
9247 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9248 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00009249
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009250 return OR_Success;
9251}
9252
John McCall53262c92010-01-12 02:15:36 +00009253namespace {
9254
9255enum OverloadCandidateKind {
9256 oc_function,
9257 oc_method,
9258 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00009259 oc_function_template,
9260 oc_method_template,
9261 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00009262 oc_implicit_default_constructor,
9263 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009264 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00009265 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00009266 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00009267 oc_inherited_constructor,
9268 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00009269};
9270
George Burgess IVd66d37c2016-10-28 21:42:06 +00009271static OverloadCandidateKind
9272ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9273 std::string &Description) {
John McCalle1ac8d12010-01-13 00:25:19 +00009274 bool isTemplate = false;
9275
9276 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9277 isTemplate = true;
9278 Description = S.getTemplateArgumentBindingsText(
9279 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9280 }
John McCallfd0b2f82010-01-06 09:43:14 +00009281
9282 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00009283 if (!Ctor->isImplicit()) {
9284 if (isa<ConstructorUsingShadowDecl>(Found))
9285 return isTemplate ? oc_inherited_constructor_template
9286 : oc_inherited_constructor;
9287 else
9288 return isTemplate ? oc_constructor_template : oc_constructor;
9289 }
Sebastian Redl08905022011-02-05 19:23:19 +00009290
Alexis Hunt119c10e2011-05-25 23:16:36 +00009291 if (Ctor->isDefaultConstructor())
9292 return oc_implicit_default_constructor;
9293
9294 if (Ctor->isMoveConstructor())
9295 return oc_implicit_move_constructor;
9296
9297 assert(Ctor->isCopyConstructor() &&
9298 "unexpected sort of implicit constructor");
9299 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00009300 }
9301
9302 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9303 // This actually gets spelled 'candidate function' for now, but
9304 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00009305 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00009306 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00009307
Alexis Hunt119c10e2011-05-25 23:16:36 +00009308 if (Meth->isMoveAssignmentOperator())
9309 return oc_implicit_move_assignment;
9310
Douglas Gregor12695102012-02-10 08:36:38 +00009311 if (Meth->isCopyAssignmentOperator())
9312 return oc_implicit_copy_assignment;
9313
9314 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9315 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00009316 }
9317
John McCalle1ac8d12010-01-13 00:25:19 +00009318 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00009319}
9320
Richard Smith5179eb72016-06-28 19:03:57 +00009321void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9322 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9323 // set.
9324 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9325 S.Diag(FoundDecl->getLocation(),
9326 diag::note_ovl_candidate_inherited_constructor)
9327 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00009328}
9329
John McCall53262c92010-01-12 02:15:36 +00009330} // end anonymous namespace
9331
George Burgess IV5f21c712015-10-12 19:57:04 +00009332static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9333 const FunctionDecl *FD) {
9334 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9335 bool AlwaysTrue;
9336 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9337 return false;
9338 if (!AlwaysTrue)
9339 return false;
9340 }
9341 return true;
9342}
9343
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009344/// \brief Returns true if we can take the address of the function.
9345///
9346/// \param Complain - If true, we'll emit a diagnostic
9347/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9348/// we in overload resolution?
9349/// \param Loc - The location of the statement we're complaining about. Ignored
9350/// if we're not complaining, or if we're in overload resolution.
9351static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9352 bool Complain,
9353 bool InOverloadResolution,
9354 SourceLocation Loc) {
9355 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9356 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009357 if (InOverloadResolution)
9358 S.Diag(FD->getLocStart(),
9359 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9360 else
9361 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9362 }
9363 return false;
9364 }
9365
George Burgess IV21081362016-07-24 23:12:40 +00009366 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9367 return P->hasAttr<PassObjectSizeAttr>();
9368 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009369 if (I == FD->param_end())
9370 return true;
9371
9372 if (Complain) {
9373 // Add one to ParamNo because it's user-facing
9374 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9375 if (InOverloadResolution)
9376 S.Diag(FD->getLocation(),
9377 diag::note_ovl_candidate_has_pass_object_size_params)
9378 << ParamNo;
9379 else
9380 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9381 << FD << ParamNo;
9382 }
9383 return false;
9384}
9385
9386static bool checkAddressOfCandidateIsAvailable(Sema &S,
9387 const FunctionDecl *FD) {
9388 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9389 /*InOverloadResolution=*/true,
9390 /*Loc=*/SourceLocation());
9391}
9392
9393bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9394 bool Complain,
9395 SourceLocation Loc) {
9396 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9397 /*InOverloadResolution=*/false,
9398 Loc);
9399}
9400
John McCall53262c92010-01-12 02:15:36 +00009401// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009402void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9403 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009404 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9405 return;
9406
John McCalle1ac8d12010-01-13 00:25:19 +00009407 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009408 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009409 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00009410 << (unsigned) K << Fn << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009411
9412 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009413 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009414 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009415}
9416
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009417// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009418// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009419void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9420 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009421 assert(OverloadedExpr->getType() == Context.OverloadTy);
9422
9423 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9424 OverloadExpr *OvlExpr = Ovl.Expression;
9425
9426 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9427 IEnd = OvlExpr->decls_end();
9428 I != IEnd; ++I) {
9429 if (FunctionTemplateDecl *FunTmpl =
9430 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009431 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009432 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009433 } else if (FunctionDecl *Fun
9434 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009435 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009436 }
9437 }
9438}
9439
John McCall0d1da222010-01-12 00:44:57 +00009440/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9441/// "lead" diagnostic; it will be given two arguments, the source and
9442/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009443void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9444 Sema &S,
9445 SourceLocation CaretLoc,
9446 const PartialDiagnostic &PDiag) const {
9447 S.Diag(CaretLoc, PDiag)
9448 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009449 // FIXME: The note limiting machinery is borrowed from
9450 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9451 // refactoring here.
9452 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9453 unsigned CandsShown = 0;
9454 AmbiguousConversionSequence::const_iterator I, E;
9455 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9456 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9457 break;
9458 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009459 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009460 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009461 if (I != E)
9462 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009463}
9464
Richard Smith17c00b42014-11-12 01:24:00 +00009465static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009466 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009467 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9468 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009469 assert(Cand->Function && "for now, candidate must be a function");
9470 FunctionDecl *Fn = Cand->Function;
9471
9472 // There's a conversion slot for the object argument if this is a
9473 // non-constructor method. Note that 'I' corresponds the
9474 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009475 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009476 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009477 if (I == 0)
9478 isObjectArgument = true;
9479 else
9480 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009481 }
9482
John McCalle1ac8d12010-01-13 00:25:19 +00009483 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009484 OverloadCandidateKind FnKind =
9485 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009486
John McCall6a61b522010-01-13 09:16:55 +00009487 Expr *FromExpr = Conv.Bad.FromExpr;
9488 QualType FromTy = Conv.Bad.getFromType();
9489 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009490
John McCallfb7ad0f2010-02-02 02:42:52 +00009491 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009492 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009493 Expr *E = FromExpr->IgnoreParens();
9494 if (isa<UnaryOperator>(E))
9495 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009496 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009497
9498 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9499 << (unsigned) FnKind << FnDesc
9500 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9501 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009502 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009503 return;
9504 }
9505
John McCall6d174642010-01-23 08:10:49 +00009506 // Do some hand-waving analysis to see if the non-viability is due
9507 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009508 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9509 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9510 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9511 CToTy = RT->getPointeeType();
9512 else {
9513 // TODO: detect and diagnose the full richness of const mismatches.
9514 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009515 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9516 CFromTy = FromPT->getPointeeType();
9517 CToTy = ToPT->getPointeeType();
9518 }
John McCall47000992010-01-14 03:28:57 +00009519 }
9520
9521 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9522 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009523 Qualifiers FromQs = CFromTy.getQualifiers();
9524 Qualifiers ToQs = CToTy.getQualifiers();
9525
9526 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9527 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9528 << (unsigned) FnKind << FnDesc
9529 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9530 << FromTy
9531 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9532 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009533 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009534 return;
9535 }
9536
John McCall31168b02011-06-15 23:02:42 +00009537 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009538 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009539 << (unsigned) FnKind << FnDesc
9540 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9541 << FromTy
9542 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9543 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009544 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009545 return;
9546 }
9547
Douglas Gregoraec25842011-04-26 23:16:46 +00009548 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9549 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9550 << (unsigned) FnKind << FnDesc
9551 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9552 << FromTy
9553 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9554 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009555 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009556 return;
9557 }
9558
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009559 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9560 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9561 << (unsigned) FnKind << FnDesc
9562 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9563 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009564 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009565 return;
9566 }
9567
John McCall47000992010-01-14 03:28:57 +00009568 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9569 assert(CVR && "unexpected qualifiers mismatch");
9570
9571 if (isObjectArgument) {
9572 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9573 << (unsigned) FnKind << FnDesc
9574 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9575 << FromTy << (CVR - 1);
9576 } else {
9577 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9578 << (unsigned) FnKind << FnDesc
9579 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9580 << FromTy << (CVR - 1) << I+1;
9581 }
Richard Smith5179eb72016-06-28 19:03:57 +00009582 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009583 return;
9584 }
9585
Sebastian Redla72462c2011-09-24 17:48:32 +00009586 // Special diagnostic for failure to convert an initializer list, since
9587 // telling the user that it has type void is not useful.
9588 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9589 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9590 << (unsigned) FnKind << FnDesc
9591 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9592 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009593 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009594 return;
9595 }
9596
John McCall6d174642010-01-23 08:10:49 +00009597 // Diagnose references or pointers to incomplete types differently,
9598 // since it's far from impossible that the incompleteness triggered
9599 // the failure.
9600 QualType TempFromTy = FromTy.getNonReferenceType();
9601 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9602 TempFromTy = PTy->getPointeeType();
9603 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009604 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009605 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9606 << (unsigned) FnKind << FnDesc
9607 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009608 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9609 << (unsigned) (Cand->Fix.Kind);
9610
Richard Smith5179eb72016-06-28 19:03:57 +00009611 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009612 return;
9613 }
9614
Douglas Gregor56f2e342010-06-30 23:01:39 +00009615 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009616 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009617 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9618 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9619 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9620 FromPtrTy->getPointeeType()) &&
9621 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9622 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009623 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009624 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009625 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009626 }
9627 } else if (const ObjCObjectPointerType *FromPtrTy
9628 = FromTy->getAs<ObjCObjectPointerType>()) {
9629 if (const ObjCObjectPointerType *ToPtrTy
9630 = ToTy->getAs<ObjCObjectPointerType>())
9631 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9632 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9633 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9634 FromPtrTy->getPointeeType()) &&
9635 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009636 BaseToDerivedConversion = 2;
9637 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009638 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9639 !FromTy->isIncompleteType() &&
9640 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009641 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009642 BaseToDerivedConversion = 3;
9643 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9644 ToTy.getNonReferenceType().getCanonicalType() ==
9645 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009646 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9647 << (unsigned) FnKind << FnDesc
9648 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9649 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009650 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009651 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009652 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009654
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009655 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009656 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009657 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009658 << (unsigned) FnKind << FnDesc
9659 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009660 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009661 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009662 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009663 return;
9664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009665
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009666 if (isa<ObjCObjectPointerType>(CFromTy) &&
9667 isa<PointerType>(CToTy)) {
9668 Qualifiers FromQs = CFromTy.getQualifiers();
9669 Qualifiers ToQs = CToTy.getQualifiers();
9670 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9671 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9672 << (unsigned) FnKind << FnDesc
9673 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9674 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009675 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009676 return;
9677 }
9678 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009679
9680 if (TakingCandidateAddress &&
9681 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9682 return;
9683
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009684 // Emit the generic diagnostic and, optionally, add the hints to it.
9685 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9686 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009687 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009688 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9689 << (unsigned) (Cand->Fix.Kind);
9690
9691 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009692 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9693 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009694 FDiag << *HI;
9695 S.Diag(Fn->getLocation(), FDiag);
9696
Richard Smith5179eb72016-06-28 19:03:57 +00009697 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009698}
9699
Larisse Voufo98b20f12013-07-19 23:00:19 +00009700/// Additional arity mismatch diagnosis specific to a function overload
9701/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9702/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009703static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9704 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009705 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009706 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009707
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009708 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009709 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009710 // right number of arguments, because only overloaded operators have
9711 // the weird behavior of overloading member and non-member functions.
9712 // Just don't report anything.
9713 if (Fn->isInvalidDecl() &&
9714 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009715 return true;
9716
9717 if (NumArgs < MinParams) {
9718 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9719 (Cand->FailureKind == ovl_fail_bad_deduction &&
9720 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9721 } else {
9722 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9723 (Cand->FailureKind == ovl_fail_bad_deduction &&
9724 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9725 }
9726
9727 return false;
9728}
9729
9730/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009731static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9732 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009733 assert(isa<FunctionDecl>(D) &&
9734 "The templated declaration should at least be a function"
9735 " when diagnosing bad template argument deduction due to too many"
9736 " or too few arguments");
9737
9738 FunctionDecl *Fn = cast<FunctionDecl>(D);
9739
9740 // TODO: treat calls to a missing default constructor as a special case
9741 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9742 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009743
John McCall6a61b522010-01-13 09:16:55 +00009744 // at least / at most / exactly
9745 unsigned mode, modeCount;
9746 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009747 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9748 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009749 mode = 0; // "at least"
9750 else
9751 mode = 2; // "exactly"
9752 modeCount = MinParams;
9753 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009754 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009755 mode = 1; // "at most"
9756 else
9757 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009758 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009759 }
9760
9761 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009762 OverloadCandidateKind FnKind =
9763 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009764
Richard Smith10ff50d2012-05-11 05:16:41 +00009765 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9766 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009767 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9768 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009769 else
9770 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009771 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9772 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009773 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009774}
9775
Larisse Voufo98b20f12013-07-19 23:00:19 +00009776/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009777static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9778 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009779 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009780 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009781}
Larisse Voufo47c08452013-07-19 22:53:23 +00009782
Richard Smith17c00b42014-11-12 01:24:00 +00009783static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009784 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9785 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009786 llvm_unreachable("Unsupported: Getting the described template declaration"
9787 " for bad deduction diagnosis");
9788}
9789
9790/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009791static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009792 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009793 unsigned NumArgs,
9794 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009795 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009796 NamedDecl *ParamD;
9797 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9798 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9799 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009800 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009801 case Sema::TDK_Success:
9802 llvm_unreachable("TDK_success while diagnosing bad deduction");
9803
9804 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009805 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009806 S.Diag(Templated->getLocation(),
9807 diag::note_ovl_candidate_incomplete_deduction)
9808 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009809 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009810 return;
9811 }
9812
John McCall42d7d192010-08-05 09:05:08 +00009813 case Sema::TDK_Underqualified: {
9814 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9815 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9816
Larisse Voufo98b20f12013-07-19 23:00:19 +00009817 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009818
9819 // Param will have been canonicalized, but it should just be a
9820 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009821 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009822 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009823 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009824 assert(S.Context.hasSameType(Param, NonCanonParam));
9825
9826 // Arg has also been canonicalized, but there's nothing we can do
9827 // about that. It also doesn't matter as much, because it won't
9828 // have any template parameters in it (because deduction isn't
9829 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009830 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009831
Larisse Voufo98b20f12013-07-19 23:00:19 +00009832 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9833 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009834 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009835 return;
9836 }
9837
9838 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009839 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009840 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009841 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009842 which = 0;
Richard Smith593d6a12016-12-23 01:30:39 +00009843 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9844 // Deduction might have failed because we deduced arguments of two
9845 // different types for a non-type template parameter.
9846 // FIXME: Use a different TDK value for this.
9847 QualType T1 =
9848 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9849 QualType T2 =
9850 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9851 if (!S.Context.hasSameType(T1, T2)) {
9852 S.Diag(Templated->getLocation(),
9853 diag::note_ovl_candidate_inconsistent_deduction_types)
9854 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9855 << *DeductionFailure.getSecondArg() << T2;
9856 MaybeEmitInheritedConstructorNote(S, Found);
9857 return;
9858 }
9859
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009860 which = 1;
Richard Smith593d6a12016-12-23 01:30:39 +00009861 } else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009862 which = 2;
9863 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009864
Larisse Voufo98b20f12013-07-19 23:00:19 +00009865 S.Diag(Templated->getLocation(),
9866 diag::note_ovl_candidate_inconsistent_deduction)
9867 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9868 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009869 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009870 return;
9871 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009872
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009873 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009874 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009875 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009876 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009877 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009878 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009879 else {
9880 int index = 0;
9881 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9882 index = TTP->getIndex();
9883 else if (NonTypeTemplateParmDecl *NTTP
9884 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9885 index = NTTP->getIndex();
9886 else
9887 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009888 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009889 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009890 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009891 }
Richard Smith5179eb72016-06-28 19:03:57 +00009892 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009893 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009894
Douglas Gregor02eb4832010-05-08 18:13:28 +00009895 case Sema::TDK_TooManyArguments:
9896 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009897 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009898 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009899
9900 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009901 S.Diag(Templated->getLocation(),
9902 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009903 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009904 return;
9905
9906 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009907 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009908 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009909 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009910 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009911 TemplateArgString = " ";
9912 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009913 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009914 }
9915
Richard Smith6f8d2c62012-05-09 05:17:00 +00009916 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009917 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009918 if (PDiag && PDiag->second.getDiagID() ==
9919 diag::err_typename_nested_not_found_enable_if) {
9920 // FIXME: Use the source range of the condition, and the fully-qualified
9921 // name of the enable_if template. These are both present in PDiag.
9922 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9923 << "'enable_if'" << TemplateArgString;
9924 return;
9925 }
9926
Richard Smith9ca64612012-05-07 09:03:25 +00009927 // Format the SFINAE diagnostic into the argument string.
9928 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9929 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009930 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009931 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009932 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009933 SFINAEArgString = ": ";
9934 R = SourceRange(PDiag->first, PDiag->first);
9935 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9936 }
9937
Larisse Voufo98b20f12013-07-19 23:00:19 +00009938 S.Diag(Templated->getLocation(),
9939 diag::note_ovl_candidate_substitution_failure)
9940 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009941 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009942 return;
9943 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009944
Richard Smithc92d2062017-01-05 23:02:44 +00009945 case Sema::TDK_DeducedMismatch:
9946 case Sema::TDK_DeducedMismatchNested: {
Richard Smith9b534542015-12-31 02:02:54 +00009947 // Format the template argument list into the argument string.
9948 SmallString<128> TemplateArgString;
9949 if (TemplateArgumentList *Args =
9950 DeductionFailure.getTemplateArgumentList()) {
9951 TemplateArgString = " ";
9952 TemplateArgString += S.getTemplateArgumentBindingsText(
9953 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9954 }
9955
9956 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9957 << (*DeductionFailure.getCallArgIndex() + 1)
9958 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
Richard Smithc92d2062017-01-05 23:02:44 +00009959 << TemplateArgString
9960 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
Richard Smith9b534542015-12-31 02:02:54 +00009961 break;
9962 }
9963
Richard Trieue3732352013-04-08 21:11:40 +00009964 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009965 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009966 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9967 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009968 if (FirstTA.getKind() == TemplateArgument::Template &&
9969 SecondTA.getKind() == TemplateArgument::Template) {
9970 TemplateName FirstTN = FirstTA.getAsTemplate();
9971 TemplateName SecondTN = SecondTA.getAsTemplate();
9972 if (FirstTN.getKind() == TemplateName::Template &&
9973 SecondTN.getKind() == TemplateName::Template) {
9974 if (FirstTN.getAsTemplateDecl()->getName() ==
9975 SecondTN.getAsTemplateDecl()->getName()) {
9976 // FIXME: This fixes a bad diagnostic where both templates are named
9977 // the same. This particular case is a bit difficult since:
9978 // 1) It is passed as a string to the diagnostic printer.
9979 // 2) The diagnostic printer only attempts to find a better
9980 // name for types, not decls.
9981 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009982 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009983 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9984 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9985 return;
9986 }
9987 }
9988 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009989
9990 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9991 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9992 return;
9993
Faisal Vali2b391ab2013-09-26 19:54:12 +00009994 // FIXME: For generic lambda parameters, check if the function is a lambda
9995 // call operator, and if so, emit a prettier and more informative
9996 // diagnostic that mentions 'auto' and lambda in addition to
9997 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009998 S.Diag(Templated->getLocation(),
9999 diag::note_ovl_candidate_non_deduced_mismatch)
10000 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +000010001 return;
Richard Trieue3732352013-04-08 21:11:40 +000010002 }
John McCall8b9ed552010-02-01 18:53:26 +000010003 // TODO: diagnose these individually, then kill off
10004 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +000010005 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010006 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +000010007 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +000010008 return;
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010009 case Sema::TDK_CUDATargetMismatch:
10010 S.Diag(Templated->getLocation(),
10011 diag::note_cuda_ovl_candidate_target_mismatch);
10012 return;
John McCall8b9ed552010-02-01 18:53:26 +000010013 }
10014}
10015
Larisse Voufo98b20f12013-07-19 23:00:19 +000010016/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +000010017static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010018 unsigned NumArgs,
10019 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010020 unsigned TDK = Cand->DeductionFailure.Result;
10021 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10022 if (CheckArityMismatch(S, Cand, NumArgs))
10023 return;
10024 }
Richard Smithc2bebe92016-05-11 20:37:46 +000010025 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010026 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010027}
10028
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010029/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +000010030static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010031 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10032 FunctionDecl *Callee = Cand->Function;
10033
10034 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10035 CalleeTarget = S.IdentifyCUDATarget(Callee);
10036
10037 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +000010038 OverloadCandidateKind FnKind =
10039 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010040
10041 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010042 << (unsigned)FnKind << CalleeTarget << CallerTarget;
10043
10044 // This could be an implicit constructor for which we could not infer the
10045 // target due to a collsion. Diagnose that case.
10046 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10047 if (Meth != nullptr && Meth->isImplicit()) {
10048 CXXRecordDecl *ParentClass = Meth->getParent();
10049 Sema::CXXSpecialMember CSM;
10050
10051 switch (FnKind) {
10052 default:
10053 return;
10054 case oc_implicit_default_constructor:
10055 CSM = Sema::CXXDefaultConstructor;
10056 break;
10057 case oc_implicit_copy_constructor:
10058 CSM = Sema::CXXCopyConstructor;
10059 break;
10060 case oc_implicit_move_constructor:
10061 CSM = Sema::CXXMoveConstructor;
10062 break;
10063 case oc_implicit_copy_assignment:
10064 CSM = Sema::CXXCopyAssignment;
10065 break;
10066 case oc_implicit_move_assignment:
10067 CSM = Sema::CXXMoveAssignment;
10068 break;
10069 };
10070
10071 bool ConstRHS = false;
10072 if (Meth->getNumParams()) {
10073 if (const ReferenceType *RT =
10074 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10075 ConstRHS = RT->getPointeeType().isConstQualified();
10076 }
10077 }
10078
10079 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10080 /* ConstRHS */ ConstRHS,
10081 /* Diagnose */ true);
10082 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010083}
10084
Richard Smith17c00b42014-11-12 01:24:00 +000010085static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010086 FunctionDecl *Callee = Cand->Function;
10087 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10088
10089 S.Diag(Callee->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000010090 diag::note_ovl_candidate_disabled_by_function_cond_attr)
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010091 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10092}
10093
Yaxun Liu5b746652016-12-18 05:18:55 +000010094static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10095 FunctionDecl *Callee = Cand->Function;
10096
10097 S.Diag(Callee->getLocation(),
10098 diag::note_ovl_candidate_disabled_by_extension);
10099}
10100
John McCall8b9ed552010-02-01 18:53:26 +000010101/// Generates a 'note' diagnostic for an overload candidate. We've
10102/// already generated a primary error at the call site.
10103///
10104/// It really does need to be a single diagnostic with its caret
10105/// pointed at the candidate declaration. Yes, this creates some
10106/// major challenges of technical writing. Yes, this makes pointing
10107/// out problems with specific arguments quite awkward. It's still
10108/// better than generating twenty screens of text for every failed
10109/// overload.
10110///
10111/// It would be great to be able to express per-candidate problems
10112/// more richly for those diagnostic clients that cared, but we'd
10113/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +000010114static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010115 unsigned NumArgs,
10116 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +000010117 FunctionDecl *Fn = Cand->Function;
10118
John McCall12f97bc2010-01-08 04:41:39 +000010119 // Note deleted candidates, but only if they're viable.
George Burgess IV177399e2017-01-09 04:12:14 +000010120 if (Cand->Viable) {
10121 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10122 std::string FnDesc;
10123 OverloadCandidateKind FnKind =
Richard Smithc2bebe92016-05-11 20:37:46 +000010124 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +000010125
George Burgess IV177399e2017-01-09 04:12:14 +000010126 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10127 << FnKind << FnDesc
10128 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10129 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10130 return;
10131 }
John McCall12f97bc2010-01-08 04:41:39 +000010132
George Burgess IV177399e2017-01-09 04:12:14 +000010133 // We don't really have anything else to say about viable candidates.
Richard Smithc2bebe92016-05-11 20:37:46 +000010134 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010135 return;
10136 }
John McCall0d1da222010-01-12 00:44:57 +000010137
John McCall6a61b522010-01-13 09:16:55 +000010138 switch (Cand->FailureKind) {
10139 case ovl_fail_too_many_arguments:
10140 case ovl_fail_too_few_arguments:
10141 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +000010142
John McCall6a61b522010-01-13 09:16:55 +000010143 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +000010144 return DiagnoseBadDeduction(S, Cand, NumArgs,
10145 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +000010146
John McCall578a1f82014-12-14 01:46:53 +000010147 case ovl_fail_illegal_constructor: {
10148 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10149 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +000010150 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +000010151 return;
10152 }
10153
John McCallfe796dd2010-01-23 05:17:32 +000010154 case ovl_fail_trivial_conversion:
10155 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +000010156 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +000010157 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010158
John McCall65eb8792010-02-25 01:37:24 +000010159 case ovl_fail_bad_conversion: {
10160 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Richard Smith6eedfe72017-01-09 08:01:21 +000010161 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +000010162 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010163 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010164
John McCall6a61b522010-01-13 09:16:55 +000010165 // FIXME: this currently happens when we're called from SemaInit
10166 // when user-conversion overload fails. Figure out how to handle
10167 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +000010168 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +000010169 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010170
10171 case ovl_fail_bad_target:
10172 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010173
10174 case ovl_fail_enable_if:
10175 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +000010176
Yaxun Liu5b746652016-12-18 05:18:55 +000010177 case ovl_fail_ext_disabled:
10178 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10179
Richard Smithf9c59b72017-01-08 21:45:44 +000010180 case ovl_fail_inhctor_slice:
Richard Smith836a3b42017-01-13 20:46:54 +000010181 // It's generally not interesting to note copy/move constructors here.
10182 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10183 return;
Richard Smithf9c59b72017-01-08 21:45:44 +000010184 S.Diag(Fn->getLocation(),
Richard Smith836a3b42017-01-13 20:46:54 +000010185 diag::note_ovl_candidate_inherited_constructor_slice)
10186 << (Fn->getPrimaryTemplate() ? 1 : 0)
10187 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
Richard Smithf9c59b72017-01-08 21:45:44 +000010188 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10189 return;
10190
George Burgess IV7204ed92016-01-07 02:26:57 +000010191 case ovl_fail_addr_not_available: {
10192 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10193 (void)Available;
10194 assert(!Available);
10195 break;
10196 }
John McCall65eb8792010-02-25 01:37:24 +000010197 }
John McCalld3224162010-01-08 00:58:21 +000010198}
10199
Richard Smith17c00b42014-11-12 01:24:00 +000010200static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +000010201 // Desugar the type of the surrogate down to a function type,
10202 // retaining as many typedefs as possible while still showing
10203 // the function type (and, therefore, its parameter types).
10204 QualType FnType = Cand->Surrogate->getConversionType();
10205 bool isLValueReference = false;
10206 bool isRValueReference = false;
10207 bool isPointer = false;
10208 if (const LValueReferenceType *FnTypeRef =
10209 FnType->getAs<LValueReferenceType>()) {
10210 FnType = FnTypeRef->getPointeeType();
10211 isLValueReference = true;
10212 } else if (const RValueReferenceType *FnTypeRef =
10213 FnType->getAs<RValueReferenceType>()) {
10214 FnType = FnTypeRef->getPointeeType();
10215 isRValueReference = true;
10216 }
10217 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10218 FnType = FnTypePtr->getPointeeType();
10219 isPointer = true;
10220 }
10221 // Desugar down to a function type.
10222 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10223 // Reconstruct the pointer/reference as appropriate.
10224 if (isPointer) FnType = S.Context.getPointerType(FnType);
10225 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10226 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10227
10228 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10229 << FnType;
10230}
10231
Richard Smith17c00b42014-11-12 01:24:00 +000010232static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10233 SourceLocation OpLoc,
10234 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010235 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +000010236 std::string TypeStr("operator");
10237 TypeStr += Opc;
10238 TypeStr += "(";
10239 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Richard Smith6eedfe72017-01-09 08:01:21 +000010240 if (Cand->Conversions.size() == 1) {
John McCalld3224162010-01-08 00:58:21 +000010241 TypeStr += ")";
10242 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10243 } else {
10244 TypeStr += ", ";
10245 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
10246 TypeStr += ")";
10247 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10248 }
10249}
10250
Richard Smith17c00b42014-11-12 01:24:00 +000010251static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10252 OverloadCandidate *Cand) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010253 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
John McCall0d1da222010-01-12 00:44:57 +000010254 if (ICS.isBad()) break; // all meaningless after first invalid
10255 if (!ICS.isAmbiguous()) continue;
10256
Richard Smithc2bebe92016-05-11 20:37:46 +000010257 ICS.DiagnoseAmbiguousConversion(
10258 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +000010259 }
10260}
10261
Larisse Voufo98b20f12013-07-19 23:00:19 +000010262static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +000010263 if (Cand->Function)
10264 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +000010265 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +000010266 return Cand->Surrogate->getLocation();
10267 return SourceLocation();
10268}
10269
Larisse Voufo98b20f12013-07-19 23:00:19 +000010270static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +000010271 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010272 case Sema::TDK_Success:
Richard Smith6eedfe72017-01-09 08:01:21 +000010273 case Sema::TDK_NonDependentConversionFailure:
10274 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010275
Douglas Gregorc5c01a62012-09-13 21:01:57 +000010276 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010277 case Sema::TDK_Incomplete:
10278 return 1;
10279
10280 case Sema::TDK_Underqualified:
10281 case Sema::TDK_Inconsistent:
10282 return 2;
10283
10284 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +000010285 case Sema::TDK_DeducedMismatch:
Richard Smithc92d2062017-01-05 23:02:44 +000010286 case Sema::TDK_DeducedMismatchNested:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010287 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +000010288 case Sema::TDK_MiscellaneousDeductionFailure:
Artem Belevich13e9b4d2016-12-07 19:27:16 +000010289 case Sema::TDK_CUDATargetMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010290 return 3;
10291
10292 case Sema::TDK_InstantiationDepth:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010293 return 4;
10294
10295 case Sema::TDK_InvalidExplicitArguments:
10296 return 5;
10297
10298 case Sema::TDK_TooManyArguments:
10299 case Sema::TDK_TooFewArguments:
10300 return 6;
10301 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +000010302 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010303}
10304
Richard Smith17c00b42014-11-12 01:24:00 +000010305namespace {
John McCallad2587a2010-01-12 00:48:53 +000010306struct CompareOverloadCandidatesForDisplay {
10307 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +000010308 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010309 size_t NumArgs;
10310
Richard Smith0f59cb32015-12-18 21:45:41 +000010311 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010312 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +000010313
10314 bool operator()(const OverloadCandidate *L,
10315 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +000010316 // Fast-path this check.
10317 if (L == R) return false;
10318
John McCall12f97bc2010-01-08 04:41:39 +000010319 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +000010320 if (L->Viable) {
10321 if (!R->Viable) return true;
10322
10323 // TODO: introduce a tri-valued comparison for overload
10324 // candidates. Would be more worthwhile if we had a sort
10325 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +000010326 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10327 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +000010328 } else if (R->Viable)
10329 return false;
John McCall12f97bc2010-01-08 04:41:39 +000010330
John McCall3712d9e2010-01-15 23:32:50 +000010331 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +000010332
John McCall3712d9e2010-01-15 23:32:50 +000010333 // Criteria by which we can sort non-viable candidates:
10334 if (!L->Viable) {
10335 // 1. Arity mismatches come after other candidates.
10336 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010337 L->FailureKind == ovl_fail_too_few_arguments) {
10338 if (R->FailureKind == ovl_fail_too_many_arguments ||
10339 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +000010340 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10341 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10342 if (LDist == RDist) {
10343 if (L->FailureKind == R->FailureKind)
10344 // Sort non-surrogates before surrogates.
10345 return !L->IsSurrogate && R->IsSurrogate;
10346 // Sort candidates requiring fewer parameters than there were
10347 // arguments given after candidates requiring more parameters
10348 // than there were arguments given.
10349 return L->FailureKind == ovl_fail_too_many_arguments;
10350 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010351 return LDist < RDist;
10352 }
John McCall3712d9e2010-01-15 23:32:50 +000010353 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +000010354 }
John McCall3712d9e2010-01-15 23:32:50 +000010355 if (R->FailureKind == ovl_fail_too_many_arguments ||
10356 R->FailureKind == ovl_fail_too_few_arguments)
10357 return true;
John McCall12f97bc2010-01-08 04:41:39 +000010358
John McCallfe796dd2010-01-23 05:17:32 +000010359 // 2. Bad conversions come first and are ordered by the number
10360 // of bad conversions and quality of good conversions.
10361 if (L->FailureKind == ovl_fail_bad_conversion) {
10362 if (R->FailureKind != ovl_fail_bad_conversion)
10363 return true;
10364
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010365 // The conversion that can be fixed with a smaller number of changes,
10366 // comes first.
10367 unsigned numLFixes = L->Fix.NumConversionsFixed;
10368 unsigned numRFixes = R->Fix.NumConversionsFixed;
10369 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10370 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010371 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +000010372 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +000010373 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010374
John McCallfe796dd2010-01-23 05:17:32 +000010375 // If there's any ordering between the defined conversions...
10376 // FIXME: this might not be transitive.
Richard Smith6eedfe72017-01-09 08:01:21 +000010377 assert(L->Conversions.size() == R->Conversions.size());
John McCallfe796dd2010-01-23 05:17:32 +000010378
10379 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010380 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Richard Smith6eedfe72017-01-09 08:01:21 +000010381 for (unsigned E = L->Conversions.size(); I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010382 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010383 L->Conversions[I],
10384 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010385 case ImplicitConversionSequence::Better:
10386 leftBetter++;
10387 break;
10388
10389 case ImplicitConversionSequence::Worse:
10390 leftBetter--;
10391 break;
10392
10393 case ImplicitConversionSequence::Indistinguishable:
10394 break;
10395 }
10396 }
10397 if (leftBetter > 0) return true;
10398 if (leftBetter < 0) return false;
10399
10400 } else if (R->FailureKind == ovl_fail_bad_conversion)
10401 return false;
10402
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010403 if (L->FailureKind == ovl_fail_bad_deduction) {
10404 if (R->FailureKind != ovl_fail_bad_deduction)
10405 return true;
10406
10407 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10408 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010409 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010410 } else if (R->FailureKind == ovl_fail_bad_deduction)
10411 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010412
John McCall3712d9e2010-01-15 23:32:50 +000010413 // TODO: others?
10414 }
10415
10416 // Sort everything else by location.
10417 SourceLocation LLoc = GetLocationForCandidate(L);
10418 SourceLocation RLoc = GetLocationForCandidate(R);
10419
10420 // Put candidates without locations (e.g. builtins) at the end.
10421 if (LLoc.isInvalid()) return false;
10422 if (RLoc.isInvalid()) return true;
10423
10424 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010425 }
10426};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010427}
John McCall12f97bc2010-01-08 04:41:39 +000010428
John McCallfe796dd2010-01-23 05:17:32 +000010429/// CompleteNonViableCandidate - Normally, overload resolution only
Richard Smith6eedfe72017-01-09 08:01:21 +000010430/// computes up to the first bad conversion. Produces the FixIt set if
10431/// possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010432static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10433 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010434 assert(!Cand->Viable);
10435
10436 // Don't do anything on failures other than bad conversion.
10437 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10438
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010439 // We only want the FixIts if all the arguments can be corrected.
10440 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010441 // Use a implicit copy initialization to check conversion fixes.
10442 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010443
Richard Smith6eedfe72017-01-09 08:01:21 +000010444 // Attempt to fix the bad conversion.
10445 unsigned ConvCount = Cand->Conversions.size();
10446 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10447 ++ConvIdx) {
John McCallfe796dd2010-01-23 05:17:32 +000010448 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
Richard Smith6eedfe72017-01-09 08:01:21 +000010449 if (Cand->Conversions[ConvIdx].isInitialized() &&
10450 Cand->Conversions[ConvIdx].isBad()) {
10451 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
John McCallfe796dd2010-01-23 05:17:32 +000010452 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010453 }
John McCallfe796dd2010-01-23 05:17:32 +000010454 }
10455
Douglas Gregoradc7a702010-04-16 17:45:54 +000010456 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010457 // operation somehow.
10458 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010459
Richard Smith14ead302017-01-10 20:19:21 +000010460 unsigned ConvIdx = 0;
10461 ArrayRef<QualType> ParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010462
10463 if (Cand->IsSurrogate) {
10464 QualType ConvType
10465 = Cand->Surrogate->getConversionType().getNonReferenceType();
10466 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10467 ConvType = ConvPtrType->getPointeeType();
Richard Smith14ead302017-01-10 20:19:21 +000010468 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10469 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10470 ConvIdx = 1;
John McCallfe796dd2010-01-23 05:17:32 +000010471 } else if (Cand->Function) {
Richard Smith14ead302017-01-10 20:19:21 +000010472 ParamTypes =
10473 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
John McCallfe796dd2010-01-23 05:17:32 +000010474 if (isa<CXXMethodDecl>(Cand->Function) &&
Richard Smith14ead302017-01-10 20:19:21 +000010475 !isa<CXXConstructorDecl>(Cand->Function)) {
10476 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10477 ConvIdx = 1;
Richard Smith6eedfe72017-01-09 08:01:21 +000010478 }
Richard Smith14ead302017-01-10 20:19:21 +000010479 } else {
10480 // Builtin operator.
10481 assert(ConvCount <= 3);
10482 ParamTypes = Cand->BuiltinTypes.ParamTypes;
John McCallfe796dd2010-01-23 05:17:32 +000010483 }
10484
10485 // Fill in the rest of the conversions.
Richard Smith14ead302017-01-10 20:19:21 +000010486 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +000010487 if (Cand->Conversions[ConvIdx].isInitialized()) {
Richard Smith14ead302017-01-10 20:19:21 +000010488 // We've already checked this conversion.
10489 } else if (ArgIdx < ParamTypes.size()) {
10490 if (ParamTypes[ArgIdx]->isDependentType())
Richard Smith6eedfe72017-01-09 08:01:21 +000010491 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10492 Args[ArgIdx]->getType());
10493 else {
10494 Cand->Conversions[ConvIdx] =
Richard Smith14ead302017-01-10 20:19:21 +000010495 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
Richard Smith6eedfe72017-01-09 08:01:21 +000010496 SuppressUserConversions,
10497 /*InOverloadResolution=*/true,
10498 /*AllowObjCWritebackConversion=*/
10499 S.getLangOpts().ObjCAutoRefCount);
10500 // Store the FixIt in the candidate if it exists.
10501 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10502 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10503 }
10504 } else
John McCallfe796dd2010-01-23 05:17:32 +000010505 Cand->Conversions[ConvIdx].setEllipsis();
10506 }
10507}
10508
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010509/// PrintOverloadCandidates - When overload resolution fails, prints
10510/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010511/// set.
Richard Smithb2f0f052016-10-10 18:54:32 +000010512void OverloadCandidateSet::NoteCandidates(
10513 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10514 StringRef Opc, SourceLocation OpLoc,
10515 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
John McCall12f97bc2010-01-08 04:41:39 +000010516 // Sort the candidates by viability and position. Sorting directly would
10517 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010518 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010519 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10520 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
Richard Smithb2f0f052016-10-10 18:54:32 +000010521 if (!Filter(*Cand))
10522 continue;
John McCallfe796dd2010-01-23 05:17:32 +000010523 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010524 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010525 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010526 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010527 if (Cand->Function || Cand->IsSurrogate)
10528 Cands.push_back(Cand);
10529 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10530 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010531 }
10532 }
10533
John McCallad2587a2010-01-12 00:48:53 +000010534 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010535 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010536
John McCall0d1da222010-01-12 00:44:57 +000010537 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010538
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010539 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010540 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010541 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010542 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10543 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010544
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010545 // Set an arbitrary limit on the number of candidate functions we'll spam
10546 // the user with. FIXME: This limit should depend on details of the
10547 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010548 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010549 break;
10550 }
10551 ++CandsShown;
10552
John McCalld3224162010-01-08 00:58:21 +000010553 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010554 NoteFunctionCandidate(S, Cand, Args.size(),
10555 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010556 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010557 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010558 else {
10559 assert(Cand->Viable &&
10560 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010561 // Generally we only see ambiguities including viable builtin
10562 // operators if overload resolution got screwed up by an
10563 // ambiguous user-defined conversion.
10564 //
10565 // FIXME: It's quite possible for different conversions to see
10566 // different ambiguities, though.
10567 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010568 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010569 ReportedAmbiguousConversions = true;
10570 }
John McCalld3224162010-01-08 00:58:21 +000010571
John McCall0d1da222010-01-12 00:44:57 +000010572 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010573 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010574 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010575 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010576
10577 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010578 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010579}
10580
Larisse Voufo98b20f12013-07-19 23:00:19 +000010581static SourceLocation
10582GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10583 return Cand->Specialization ? Cand->Specialization->getLocation()
10584 : SourceLocation();
10585}
10586
Richard Smith17c00b42014-11-12 01:24:00 +000010587namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010588struct CompareTemplateSpecCandidatesForDisplay {
10589 Sema &S;
10590 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10591
10592 bool operator()(const TemplateSpecCandidate *L,
10593 const TemplateSpecCandidate *R) {
10594 // Fast-path this check.
10595 if (L == R)
10596 return false;
10597
10598 // Assuming that both candidates are not matches...
10599
10600 // Sort by the ranking of deduction failures.
10601 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10602 return RankDeductionFailure(L->DeductionFailure) <
10603 RankDeductionFailure(R->DeductionFailure);
10604
10605 // Sort everything else by location.
10606 SourceLocation LLoc = GetLocationForCandidate(L);
10607 SourceLocation RLoc = GetLocationForCandidate(R);
10608
10609 // Put candidates without locations (e.g. builtins) at the end.
10610 if (LLoc.isInvalid())
10611 return false;
10612 if (RLoc.isInvalid())
10613 return true;
10614
10615 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10616 }
10617};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010618}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010619
10620/// Diagnose a template argument deduction failure.
10621/// We are treating these failures as overload failures due to bad
10622/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010623void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10624 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010625 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010626 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010627}
10628
10629void TemplateSpecCandidateSet::destroyCandidates() {
10630 for (iterator i = begin(), e = end(); i != e; ++i) {
10631 i->DeductionFailure.Destroy();
10632 }
10633}
10634
10635void TemplateSpecCandidateSet::clear() {
10636 destroyCandidates();
10637 Candidates.clear();
10638}
10639
10640/// NoteCandidates - When no template specialization match is found, prints
10641/// diagnostic messages containing the non-matching specializations that form
10642/// the candidate set.
10643/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10644/// OCD == OCD_AllCandidates and Cand->Viable == false.
10645void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10646 // Sort the candidates by position (assuming no candidate is a match).
10647 // Sorting directly would be prohibitive, so we make a set of pointers
10648 // and sort those.
10649 SmallVector<TemplateSpecCandidate *, 32> Cands;
10650 Cands.reserve(size());
10651 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10652 if (Cand->Specialization)
10653 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010654 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010655 // in general, want to list every possible builtin candidate.
10656 }
10657
10658 std::sort(Cands.begin(), Cands.end(),
10659 CompareTemplateSpecCandidatesForDisplay(S));
10660
10661 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10662 // for generalization purposes (?).
10663 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10664
10665 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10666 unsigned CandsShown = 0;
10667 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10668 TemplateSpecCandidate *Cand = *I;
10669
10670 // Set an arbitrary limit on the number of candidates we'll spam
10671 // the user with. FIXME: This limit should depend on details of the
10672 // candidate list.
10673 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10674 break;
10675 ++CandsShown;
10676
10677 assert(Cand->Specialization &&
10678 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010679 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010680 }
10681
10682 if (I != E)
10683 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10684}
10685
Douglas Gregorb491ed32011-02-19 21:32:49 +000010686// [PossiblyAFunctionType] --> [Return]
10687// NonFunctionType --> NonFunctionType
10688// R (A) --> R(A)
10689// R (*)(A) --> R (A)
10690// R (&)(A) --> R (A)
10691// R (S::*)(A) --> R (A)
10692QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10693 QualType Ret = PossiblyAFunctionType;
10694 if (const PointerType *ToTypePtr =
10695 PossiblyAFunctionType->getAs<PointerType>())
10696 Ret = ToTypePtr->getPointeeType();
10697 else if (const ReferenceType *ToTypeRef =
10698 PossiblyAFunctionType->getAs<ReferenceType>())
10699 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010700 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010701 PossiblyAFunctionType->getAs<MemberPointerType>())
10702 Ret = MemTypePtr->getPointeeType();
10703 Ret =
10704 Context.getCanonicalType(Ret).getUnqualifiedType();
10705 return Ret;
10706}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010707
Richard Smith9095e5b2016-11-01 01:31:23 +000010708static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10709 bool Complain = true) {
10710 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10711 S.DeduceReturnType(FD, Loc, Complain))
10712 return true;
10713
10714 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10715 if (S.getLangOpts().CPlusPlus1z &&
10716 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10717 !S.ResolveExceptionSpec(Loc, FPT))
10718 return true;
10719
10720 return false;
10721}
10722
Richard Smith17c00b42014-11-12 01:24:00 +000010723namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010724// A helper class to help with address of function resolution
10725// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010726class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010727 Sema& S;
10728 Expr* SourceExpr;
10729 const QualType& TargetType;
10730 QualType TargetFunctionType; // Extracted function type from target type
10731
10732 bool Complain;
10733 //DeclAccessPair& ResultFunctionAccessPair;
10734 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010735
Douglas Gregorb491ed32011-02-19 21:32:49 +000010736 bool TargetTypeIsNonStaticMemberFunction;
10737 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010738 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010739 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010740
Douglas Gregorb491ed32011-02-19 21:32:49 +000010741 OverloadExpr::FindResult OvlExprInfo;
10742 OverloadExpr *OvlExpr;
10743 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010744 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010745 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010746
Douglas Gregorb491ed32011-02-19 21:32:49 +000010747public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010748 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10749 const QualType &TargetType, bool Complain)
10750 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10751 Complain(Complain), Context(S.getASTContext()),
10752 TargetTypeIsNonStaticMemberFunction(
10753 !!TargetType->getAs<MemberPointerType>()),
10754 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010755 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010756 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010757 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10758 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010759 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010760 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010761
David Majnemera4f7c7a2013-08-01 06:13:59 +000010762 if (TargetFunctionType->isFunctionType()) {
10763 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10764 if (!UME->isImplicitAccess() &&
10765 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10766 StaticMemberFunctionFromBoundPointer = true;
10767 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10768 DeclAccessPair dap;
10769 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10770 OvlExpr, false, &dap)) {
10771 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10772 if (!Method->isStatic()) {
10773 // If the target type is a non-function type and the function found
10774 // is a non-static member function, pretend as if that was the
10775 // target, it's the only possible type to end up with.
10776 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010777
David Majnemera4f7c7a2013-08-01 06:13:59 +000010778 // And skip adding the function if its not in the proper form.
10779 // We'll diagnose this due to an empty set of functions.
10780 if (!OvlExprInfo.HasFormOfMemberPointer)
10781 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010782 }
10783
David Majnemera4f7c7a2013-08-01 06:13:59 +000010784 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010785 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010786 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010787 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010788
10789 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010790 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010791
Douglas Gregorb491ed32011-02-19 21:32:49 +000010792 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10793 // C++ [over.over]p4:
10794 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010795 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010796 if (FoundNonTemplateFunction)
10797 EliminateAllTemplateMatches();
10798 else
10799 EliminateAllExceptMostSpecializedTemplate();
10800 }
10801 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010802
Justin Lebar25c4a812016-03-29 16:24:16 +000010803 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010804 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010805 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010806
10807 bool hasComplained() const { return HasComplained; }
10808
Douglas Gregorb491ed32011-02-19 21:32:49 +000010809private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010810 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10811 QualType Discard;
10812 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +000010813 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010814 }
10815
George Burgess IV6da4c202016-03-23 02:33:58 +000010816 /// \return true if A is considered a better overload candidate for the
10817 /// desired type than B.
10818 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10819 // If A doesn't have exactly the correct type, we don't want to classify it
10820 // as "better" than anything else. This way, the user is required to
10821 // disambiguate for us if there are multiple candidates and no exact match.
10822 return candidateHasExactlyCorrectType(A) &&
10823 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010824 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010825 }
10826
10827 /// \return true if we were able to eliminate all but one overload candidate,
10828 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010829 bool eliminiateSuboptimalOverloadCandidates() {
10830 // Same algorithm as overload resolution -- one pass to pick the "best",
10831 // another pass to be sure that nothing is better than the best.
10832 auto Best = Matches.begin();
10833 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10834 if (isBetterCandidate(I->second, Best->second))
10835 Best = I;
10836
10837 const FunctionDecl *BestFn = Best->second;
10838 auto IsBestOrInferiorToBest = [this, BestFn](
10839 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10840 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10841 };
10842
10843 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10844 // option, so we can potentially give the user a better error
10845 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10846 return false;
10847 Matches[0] = *Best;
10848 Matches.resize(1);
10849 return true;
10850 }
10851
Douglas Gregorb491ed32011-02-19 21:32:49 +000010852 bool isTargetTypeAFunction() const {
10853 return TargetFunctionType->isFunctionType();
10854 }
10855
10856 // [ToType] [Return]
10857
10858 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10859 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10860 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10861 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10862 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10863 }
10864
10865 // return true if any matching specializations were found
10866 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10867 const DeclAccessPair& CurAccessFunPair) {
10868 if (CXXMethodDecl *Method
10869 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10870 // Skip non-static function templates when converting to pointer, and
10871 // static when converting to member pointer.
10872 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10873 return false;
10874 }
10875 else if (TargetTypeIsNonStaticMemberFunction)
10876 return false;
10877
10878 // C++ [over.over]p2:
10879 // If the name is a function template, template argument deduction is
10880 // done (14.8.2.2), and if the argument deduction succeeds, the
10881 // resulting template argument list is used to generate a single
10882 // function template specialization, which is added to the set of
10883 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010884 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010885 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010886 if (Sema::TemplateDeductionResult Result
10887 = S.DeduceTemplateArguments(FunctionTemplate,
10888 &OvlExplicitTemplateArgs,
10889 TargetFunctionType, Specialization,
Richard Smithbaa47832016-12-01 02:11:49 +000010890 Info, /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010891 // Make a note of the failed deduction for diagnostics.
10892 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010893 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010894 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010895 return false;
10896 }
10897
Douglas Gregor19a41f12013-04-17 08:45:07 +000010898 // Template argument deduction ensures that we have an exact match or
10899 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010900 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010901 assert(S.isSameOrCompatibleFunctionType(
10902 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010903 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010904
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010905 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010906 return false;
10907
Douglas Gregorb491ed32011-02-19 21:32:49 +000010908 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10909 return true;
10910 }
10911
10912 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10913 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010914 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010915 // Skip non-static functions when converting to pointer, and static
10916 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010917 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10918 return false;
10919 }
10920 else if (TargetTypeIsNonStaticMemberFunction)
10921 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010922
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010923 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010924 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010925 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010926 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010927 return false;
10928
Richard Smith2a7d4812013-05-04 07:00:32 +000010929 // If any candidate has a placeholder return type, trigger its deduction
10930 // now.
Richard Smith9095e5b2016-11-01 01:31:23 +000010931 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10932 Complain)) {
George Burgess IV5f2ef452015-10-12 18:40:58 +000010933 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010934 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010935 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010936
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010937 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010938 return false;
10939
George Burgess IV6da4c202016-03-23 02:33:58 +000010940 // If we're in C, we need to support types that aren't exactly identical.
10941 if (!S.getLangOpts().CPlusPlus ||
10942 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010943 Matches.push_back(std::make_pair(
10944 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010945 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010946 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010947 }
Mike Stump11289f42009-09-09 15:08:12 +000010948 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010949
10950 return false;
10951 }
10952
10953 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10954 bool Ret = false;
10955
10956 // If the overload expression doesn't have the form of a pointer to
10957 // member, don't try to convert it to a pointer-to-member type.
10958 if (IsInvalidFormOfPointerToMemberFunction())
10959 return false;
10960
10961 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10962 E = OvlExpr->decls_end();
10963 I != E; ++I) {
10964 // Look through any using declarations to find the underlying function.
10965 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10966
10967 // C++ [over.over]p3:
10968 // Non-member functions and static member functions match
10969 // targets of type "pointer-to-function" or "reference-to-function."
10970 // Nonstatic member functions match targets of
10971 // type "pointer-to-member-function."
10972 // Note that according to DR 247, the containing class does not matter.
10973 if (FunctionTemplateDecl *FunctionTemplate
10974 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10975 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10976 Ret = true;
10977 }
10978 // If we have explicit template arguments supplied, skip non-templates.
10979 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10980 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10981 Ret = true;
10982 }
10983 assert(Ret || Matches.empty());
10984 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010985 }
10986
Douglas Gregorb491ed32011-02-19 21:32:49 +000010987 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010988 // [...] and any given function template specialization F1 is
10989 // eliminated if the set contains a second function template
10990 // specialization whose function template is more specialized
10991 // than the function template of F1 according to the partial
10992 // ordering rules of 14.5.5.2.
10993
10994 // The algorithm specified above is quadratic. We instead use a
10995 // two-pass algorithm (similar to the one used to identify the
10996 // best viable function in an overload set) that identifies the
10997 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010998
10999 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11000 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11001 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011002
Larisse Voufo98b20f12013-07-19 23:00:19 +000011003 // TODO: It looks like FailedCandidates does not serve much purpose
11004 // here, since the no_viable diagnostic has index 0.
11005 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000011006 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000011007 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000011008 S.PDiag(diag::err_addr_ovl_ambiguous)
11009 << Matches[0].second->getDeclName(),
11010 S.PDiag(diag::note_ovl_candidate)
11011 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000011012 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011013
Douglas Gregorb491ed32011-02-19 21:32:49 +000011014 if (Result != MatchesCopy.end()) {
11015 // Make it the first and only element
11016 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11017 Matches[0].second = cast<FunctionDecl>(*Result);
11018 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000011019 } else
11020 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000011021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011022
Douglas Gregorb491ed32011-02-19 21:32:49 +000011023 void EliminateAllTemplateMatches() {
11024 // [...] any function template specializations in the set are
11025 // eliminated if the set also contains a non-template function, [...]
11026 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011027 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011028 ++I;
11029 else {
11030 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000011031 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011032 }
11033 }
11034 }
11035
Artem Belevich94a55e82015-09-22 17:22:59 +000011036 void EliminateSuboptimalCudaMatches() {
11037 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11038 }
11039
Douglas Gregorb491ed32011-02-19 21:32:49 +000011040public:
11041 void ComplainNoMatchesFound() const {
11042 assert(Matches.empty());
11043 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11044 << OvlExpr->getName() << TargetFunctionType
11045 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000011046 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000011047 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11048 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011049 else {
11050 // We have some deduction failure messages. Use them to diagnose
11051 // the function templates, and diagnose the non-template candidates
11052 // normally.
11053 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11054 IEnd = OvlExpr->decls_end();
11055 I != IEnd; ++I)
11056 if (FunctionDecl *Fun =
11057 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011058 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000011059 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011060 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000011061 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11062 }
11063 }
11064
Douglas Gregorb491ed32011-02-19 21:32:49 +000011065 bool IsInvalidFormOfPointerToMemberFunction() const {
11066 return TargetTypeIsNonStaticMemberFunction &&
11067 !OvlExprInfo.HasFormOfMemberPointer;
11068 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011069
Douglas Gregorb491ed32011-02-19 21:32:49 +000011070 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11071 // TODO: Should we condition this on whether any functions might
11072 // have matched, or is it more appropriate to do that in callers?
11073 // TODO: a fixit wouldn't hurt.
11074 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11075 << TargetType << OvlExpr->getSourceRange();
11076 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000011077
11078 bool IsStaticMemberFunctionFromBoundPointer() const {
11079 return StaticMemberFunctionFromBoundPointer;
11080 }
11081
11082 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11083 S.Diag(OvlExpr->getLocStart(),
11084 diag::err_invalid_form_pointer_member_function)
11085 << OvlExpr->getSourceRange();
11086 }
11087
Douglas Gregorb491ed32011-02-19 21:32:49 +000011088 void ComplainOfInvalidConversion() const {
11089 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11090 << OvlExpr->getName() << TargetType;
11091 }
11092
11093 void ComplainMultipleMatchesFound() const {
11094 assert(Matches.size() > 1);
11095 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11096 << OvlExpr->getName()
11097 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000011098 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11099 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011100 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011101
11102 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11103
Douglas Gregorb491ed32011-02-19 21:32:49 +000011104 int getNumMatches() const { return Matches.size(); }
11105
11106 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011107 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011108 return Matches[0].second;
11109 }
11110
11111 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000011112 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000011113 return &Matches[0].first;
11114 }
11115};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011116}
Richard Smith17c00b42014-11-12 01:24:00 +000011117
Douglas Gregorb491ed32011-02-19 21:32:49 +000011118/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11119/// an overloaded function (C++ [over.over]), where @p From is an
11120/// expression with overloaded function type and @p ToType is the type
11121/// we're trying to resolve to. For example:
11122///
11123/// @code
11124/// int f(double);
11125/// int f(int);
11126///
11127/// int (*pfd)(double) = f; // selects f(double)
11128/// @endcode
11129///
11130/// This routine returns the resulting FunctionDecl if it could be
11131/// resolved, and NULL otherwise. When @p Complain is true, this
11132/// routine will emit diagnostics if there is an error.
11133FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011134Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11135 QualType TargetType,
11136 bool Complain,
11137 DeclAccessPair &FoundResult,
11138 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011139 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011140
11141 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11142 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011143 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000011144 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000011145 bool ShouldComplain = Complain && !Resolver.hasComplained();
11146 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011147 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11148 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11149 else
11150 Resolver.ComplainNoMatchesFound();
11151 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000011152 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000011153 Resolver.ComplainMultipleMatchesFound();
11154 else if (NumMatches == 1) {
11155 Fn = Resolver.getMatchingFunctionDecl();
11156 assert(Fn);
Richard Smith9095e5b2016-11-01 01:31:23 +000011157 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11158 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011159 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000011160 if (Complain) {
11161 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11162 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11163 else
11164 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11165 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000011166 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000011167
11168 if (pHadMultipleCandidates)
11169 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000011170 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000011171}
11172
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011173/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011174/// resolve that function to a single function that can have its address taken.
11175/// This will modify `Pair` iff it returns non-null.
11176///
11177/// This routine can only realistically succeed if all but one candidates in the
11178/// overload set for SrcExpr cannot have their addresses taken.
11179FunctionDecl *
11180Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11181 DeclAccessPair &Pair) {
11182 OverloadExpr::FindResult R = OverloadExpr::find(E);
11183 OverloadExpr *Ovl = R.Expression;
11184 FunctionDecl *Result = nullptr;
11185 DeclAccessPair DAP;
11186 // Don't use the AddressOfResolver because we're specifically looking for
11187 // cases where we have one overload candidate that lacks
11188 // enable_if/pass_object_size/...
11189 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11190 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11191 if (!FD)
11192 return nullptr;
11193
11194 if (!checkAddressOfFunctionIsAvailable(FD))
11195 continue;
11196
11197 // We have more than one result; quit.
11198 if (Result)
11199 return nullptr;
11200 DAP = I.getPair();
11201 Result = FD;
11202 }
11203
11204 if (Result)
11205 Pair = DAP;
11206 return Result;
11207}
11208
George Burgess IVbeca4a32016-06-08 00:34:22 +000011209/// \brief Given an overloaded function, tries to turn it into a non-overloaded
11210/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11211/// will perform access checks, diagnose the use of the resultant decl, and, if
11212/// necessary, perform a function-to-pointer decay.
11213///
11214/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11215/// Otherwise, returns true. This may emit diagnostics and return true.
11216bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11217 ExprResult &SrcExpr) {
11218 Expr *E = SrcExpr.get();
11219 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11220
11221 DeclAccessPair DAP;
11222 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11223 if (!Found)
11224 return false;
11225
11226 // Emitting multiple diagnostics for a function that is both inaccessible and
11227 // unavailable is consistent with our behavior elsewhere. So, always check
11228 // for both.
11229 DiagnoseUseOfDecl(Found, E->getExprLoc());
11230 CheckAddressOfMemberAccess(E, DAP);
11231 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11232 if (Fixed->getType()->isFunctionType())
11233 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11234 else
11235 SrcExpr = Fixed;
11236 return true;
11237}
11238
George Burgess IV3cde9bf2016-03-19 21:36:10 +000011239/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011240/// resolve that overloaded function expression down to a single function.
11241///
11242/// This routine can only resolve template-ids that refer to a single function
11243/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011244/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011245/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000011246///
11247/// If no template-ids are found, no diagnostics are emitted and NULL is
11248/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000011249FunctionDecl *
11250Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11251 bool Complain,
11252 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011253 // C++ [over.over]p1:
11254 // [...] [Note: any redundant set of parentheses surrounding the
11255 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011256 // C++ [over.over]p1:
11257 // [...] The overloaded function name can be preceded by the &
11258 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011259
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011260 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000011261 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000011262 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000011263
11264 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000011265 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000011266 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011267
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011268 // Look through all of the overloaded functions, searching for one
11269 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000011270 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011271 for (UnresolvedSetIterator I = ovl->decls_begin(),
11272 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011273 // C++0x [temp.arg.explicit]p3:
11274 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011275 // where deduction is not done, if a template argument list is
11276 // specified and it, along with any default template arguments,
11277 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011278 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000011279 FunctionTemplateDecl *FunctionTemplate
11280 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011281
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011282 // C++ [over.over]p2:
11283 // If the name is a function template, template argument deduction is
11284 // done (14.8.2.2), and if the argument deduction succeeds, the
11285 // resulting template argument list is used to generate a single
11286 // function template specialization, which is added to the set of
11287 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000011288 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000011289 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011290 if (TemplateDeductionResult Result
11291 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000011292 Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +000011293 /*IsAddressOfFunction*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000011294 // Make a note of the failed deduction for diagnostics.
11295 // TODO: Actually use the failed-deduction info?
11296 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000011297 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000011298 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011299 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011300 }
11301
John McCall0009fcc2011-04-26 20:42:42 +000011302 assert(Specialization && "no specialization and no error?");
11303
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011304 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000011305 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000011306 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000011307 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11308 << ovl->getName();
11309 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000011310 }
Craig Topperc3ec1492014-05-26 06:22:03 +000011311 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000011312 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000011313
John McCall0009fcc2011-04-26 20:42:42 +000011314 Matched = Specialization;
11315 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011317
Richard Smith9095e5b2016-11-01 01:31:23 +000011318 if (Matched &&
11319 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000011320 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000011321
Douglas Gregor8364e6b2009-12-21 23:17:24 +000011322 return Matched;
11323}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011324
Douglas Gregor1beec452011-03-12 01:48:56 +000011325
11326
11327
John McCall50a2c2c2011-10-11 23:14:30 +000011328// Resolve and fix an overloaded expression that can be resolved
11329// because it identifies a single function template specialization.
11330//
Douglas Gregor1beec452011-03-12 01:48:56 +000011331// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000011332//
11333// Return true if it was logically possible to so resolve the
11334// expression, regardless of whether or not it succeeded. Always
11335// returns true if 'complain' is set.
11336bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11337 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000011338 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000011339 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000011340 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000011341 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000011342
John McCall50a2c2c2011-10-11 23:14:30 +000011343 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000011344
John McCall0009fcc2011-04-26 20:42:42 +000011345 DeclAccessPair found;
11346 ExprResult SingleFunctionExpression;
11347 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11348 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011349 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000011350 SrcExpr = ExprError();
11351 return true;
11352 }
John McCall0009fcc2011-04-26 20:42:42 +000011353
11354 // It is only correct to resolve to an instance method if we're
11355 // resolving a form that's permitted to be a pointer to member.
11356 // Otherwise we'll end up making a bound member expression, which
11357 // is illegal in all the contexts we resolve like this.
11358 if (!ovl.HasFormOfMemberPointer &&
11359 isa<CXXMethodDecl>(fn) &&
11360 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000011361 if (!complain) return false;
11362
11363 Diag(ovl.Expression->getExprLoc(),
11364 diag::err_bound_member_function)
11365 << 0 << ovl.Expression->getSourceRange();
11366
11367 // TODO: I believe we only end up here if there's a mix of
11368 // static and non-static candidates (otherwise the expression
11369 // would have 'bound member' type, not 'overload' type).
11370 // Ideally we would note which candidate was chosen and why
11371 // the static candidates were rejected.
11372 SrcExpr = ExprError();
11373 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011374 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011375
Sylvestre Ledrua5202662012-07-31 06:56:50 +000011376 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000011377 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011378 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000011379
11380 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000011381 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000011382 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011383 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000011384 if (SingleFunctionExpression.isInvalid()) {
11385 SrcExpr = ExprError();
11386 return true;
11387 }
11388 }
John McCall0009fcc2011-04-26 20:42:42 +000011389 }
11390
11391 if (!SingleFunctionExpression.isUsable()) {
11392 if (complain) {
11393 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11394 << ovl.Expression->getName()
11395 << DestTypeForComplaining
11396 << OpRangeForComplaining
11397 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011398 NoteAllOverloadCandidates(SrcExpr.get());
11399
11400 SrcExpr = ExprError();
11401 return true;
11402 }
11403
11404 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011405 }
11406
John McCall50a2c2c2011-10-11 23:14:30 +000011407 SrcExpr = SingleFunctionExpression;
11408 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011409}
11410
Douglas Gregorcabea402009-09-22 15:41:20 +000011411/// \brief Add a single candidate to the overload set.
11412static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011413 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011414 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011415 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011416 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011417 bool PartialOverloading,
11418 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011419 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011420 if (isa<UsingShadowDecl>(Callee))
11421 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11422
Douglas Gregorcabea402009-09-22 15:41:20 +000011423 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011424 if (ExplicitTemplateArgs) {
11425 assert(!KnownValid && "Explicit template arguments?");
11426 return;
11427 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011428 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11429 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011430 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011431 return;
John McCalld14a8642009-11-21 08:51:07 +000011432 }
11433
11434 if (FunctionTemplateDecl *FuncTemplate
11435 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011436 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011437 ExplicitTemplateArgs, Args, CandidateSet,
11438 /*SuppressUsedConversions=*/false,
11439 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011440 return;
11441 }
11442
Richard Smith95ce4f62011-06-26 22:19:54 +000011443 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011444}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011445
Douglas Gregorcabea402009-09-22 15:41:20 +000011446/// \brief Add the overload candidates named by callee and/or found by argument
11447/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011448void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011449 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011450 OverloadCandidateSet &CandidateSet,
11451 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011452
11453#ifndef NDEBUG
11454 // Verify that ArgumentDependentLookup is consistent with the rules
11455 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011456 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011457 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11458 // and let Y be the lookup set produced by argument dependent
11459 // lookup (defined as follows). If X contains
11460 //
11461 // -- a declaration of a class member, or
11462 //
11463 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011464 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011465 //
11466 // -- a declaration that is neither a function or a function
11467 // template
11468 //
11469 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011470
John McCall57500772009-12-16 12:17:52 +000011471 if (ULE->requiresADL()) {
11472 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11473 E = ULE->decls_end(); I != E; ++I) {
11474 assert(!(*I)->getDeclContext()->isRecord());
11475 assert(isa<UsingShadowDecl>(*I) ||
11476 !(*I)->getDeclContext()->isFunctionOrMethod());
11477 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011478 }
11479 }
11480#endif
11481
John McCall57500772009-12-16 12:17:52 +000011482 // It would be nice to avoid this copy.
11483 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011484 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011485 if (ULE->hasExplicitTemplateArgs()) {
11486 ULE->copyTemplateArgumentsInto(TABuffer);
11487 ExplicitTemplateArgs = &TABuffer;
11488 }
11489
11490 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11491 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011492 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11493 CandidateSet, PartialOverloading,
11494 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011495
John McCall57500772009-12-16 12:17:52 +000011496 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011497 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011498 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011499 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011500}
John McCalld681c392009-12-16 08:11:27 +000011501
Richard Smith0603bbb2013-06-12 22:56:54 +000011502/// Determine whether a declaration with the specified name could be moved into
11503/// a different namespace.
11504static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11505 switch (Name.getCXXOverloadedOperator()) {
11506 case OO_New: case OO_Array_New:
11507 case OO_Delete: case OO_Array_Delete:
11508 return false;
11509
11510 default:
11511 return true;
11512 }
11513}
11514
Richard Smith998a5912011-06-05 22:42:48 +000011515/// Attempt to recover from an ill-formed use of a non-dependent name in a
11516/// template, where the non-dependent name was declared after the template
11517/// was defined. This is common in code written for a compilers which do not
11518/// correctly implement two-stage name lookup.
11519///
11520/// Returns true if a viable candidate was found and a diagnostic was issued.
11521static bool
11522DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11523 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011524 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011525 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011526 ArrayRef<Expr *> Args,
11527 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith51ec0cf2017-02-21 01:17:38 +000011528 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
Richard Smith998a5912011-06-05 22:42:48 +000011529 return false;
11530
11531 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011532 if (DC->isTransparentContext())
11533 continue;
11534
Richard Smith998a5912011-06-05 22:42:48 +000011535 SemaRef.LookupQualifiedName(R, DC);
11536
11537 if (!R.empty()) {
11538 R.suppressDiagnostics();
11539
11540 if (isa<CXXRecordDecl>(DC)) {
11541 // Don't diagnose names we find in classes; we get much better
11542 // diagnostics for these from DiagnoseEmptyLookup.
11543 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011544 if (DoDiagnoseEmptyLookup)
11545 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011546 return false;
11547 }
11548
Richard Smith100b24a2014-04-17 01:52:14 +000011549 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011550 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11551 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011552 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011553 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011554
11555 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011556 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011557 // No viable functions. Don't bother the user with notes for functions
11558 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011559 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011560 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011561 }
Richard Smith998a5912011-06-05 22:42:48 +000011562
11563 // Find the namespaces where ADL would have looked, and suggest
11564 // declaring the function there instead.
11565 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11566 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011567 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011568 AssociatedNamespaces,
11569 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011570 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011571 if (canBeDeclaredInNamespace(R.getLookupName())) {
11572 DeclContext *Std = SemaRef.getStdNamespace();
11573 for (Sema::AssociatedNamespaceSet::iterator
11574 it = AssociatedNamespaces.begin(),
11575 end = AssociatedNamespaces.end(); it != end; ++it) {
11576 // Never suggest declaring a function within namespace 'std'.
11577 if (Std && Std->Encloses(*it))
11578 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011579
Richard Smith0603bbb2013-06-12 22:56:54 +000011580 // Never suggest declaring a function within a namespace with a
11581 // reserved name, like __gnu_cxx.
11582 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11583 if (NS &&
11584 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11585 continue;
11586
11587 SuggestedNamespaces.insert(*it);
11588 }
Richard Smith998a5912011-06-05 22:42:48 +000011589 }
11590
11591 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11592 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011593 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011594 SemaRef.Diag(Best->Function->getLocation(),
11595 diag::note_not_found_by_two_phase_lookup)
11596 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011597 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011598 SemaRef.Diag(Best->Function->getLocation(),
11599 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011600 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011601 } else {
11602 // FIXME: It would be useful to list the associated namespaces here,
11603 // but the diagnostics infrastructure doesn't provide a way to produce
11604 // a localized representation of a list of items.
11605 SemaRef.Diag(Best->Function->getLocation(),
11606 diag::note_not_found_by_two_phase_lookup)
11607 << R.getLookupName() << 2;
11608 }
11609
11610 // Try to recover by calling this function.
11611 return true;
11612 }
11613
11614 R.clear();
11615 }
11616
11617 return false;
11618}
11619
11620/// Attempt to recover from ill-formed use of a non-dependent operator in a
11621/// template, where the non-dependent operator was declared after the template
11622/// was defined.
11623///
11624/// Returns true if a viable candidate was found and a diagnostic was issued.
11625static bool
11626DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11627 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011628 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011629 DeclarationName OpName =
11630 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11631 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11632 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011633 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011634 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011635}
11636
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011637namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011638class BuildRecoveryCallExprRAII {
11639 Sema &SemaRef;
11640public:
11641 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11642 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11643 SemaRef.IsBuildingRecoveryCallExpr = true;
11644 }
11645
11646 ~BuildRecoveryCallExprRAII() {
11647 SemaRef.IsBuildingRecoveryCallExpr = false;
11648 }
11649};
11650
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011651}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011652
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011653static std::unique_ptr<CorrectionCandidateCallback>
11654MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11655 bool HasTemplateArgs, bool AllowTypoCorrection) {
11656 if (!AllowTypoCorrection)
11657 return llvm::make_unique<NoTypoCorrectionCCC>();
11658 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11659 HasTemplateArgs, ME);
11660}
11661
John McCalld681c392009-12-16 08:11:27 +000011662/// Attempts to recover from a call where no functions were found.
11663///
11664/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011665static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011666BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011667 UnresolvedLookupExpr *ULE,
11668 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011669 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011670 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011671 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011672 // Do not try to recover if it is already building a recovery call.
11673 // This stops infinite loops for template instantiations like
11674 //
11675 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11676 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11677 //
11678 if (SemaRef.IsBuildingRecoveryCallExpr)
11679 return ExprError();
11680 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011681
11682 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011683 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011684 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011685
John McCall57500772009-12-16 12:17:52 +000011686 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011687 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011688 if (ULE->hasExplicitTemplateArgs()) {
11689 ULE->copyTemplateArgumentsInto(TABuffer);
11690 ExplicitTemplateArgs = &TABuffer;
11691 }
11692
John McCalld681c392009-12-16 08:11:27 +000011693 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11694 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011695 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011696 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011697 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011698 ExplicitTemplateArgs, Args,
11699 &DoDiagnoseEmptyLookup) &&
11700 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11701 S, SS, R,
11702 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11703 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11704 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011705 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011706
John McCall57500772009-12-16 12:17:52 +000011707 assert(!R.empty() && "lookup results empty despite recovery");
11708
Richard Smith151c4562016-12-20 21:35:28 +000011709 // If recovery created an ambiguity, just bail out.
11710 if (R.isAmbiguous()) {
11711 R.suppressDiagnostics();
11712 return ExprError();
11713 }
11714
John McCall57500772009-12-16 12:17:52 +000011715 // Build an implicit member call if appropriate. Just drop the
11716 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011717 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011718 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011719 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11720 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011721 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011722 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011723 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011724 else
11725 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11726
11727 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011728 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011729
11730 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011731 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011732 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011733 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011734 MultiExprArg(Args.data(), Args.size()),
11735 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011736}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011737
Sam Panzer0f384432012-08-21 00:52:01 +000011738/// \brief Constructs and populates an OverloadedCandidateSet from
11739/// the given function.
11740/// \returns true when an the ExprResult output parameter has been set.
11741bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11742 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011743 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011744 SourceLocation RParenLoc,
11745 OverloadCandidateSet *CandidateSet,
11746 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011747#ifndef NDEBUG
11748 if (ULE->requiresADL()) {
11749 // To do ADL, we must have found an unqualified name.
11750 assert(!ULE->getQualifier() && "qualified name with ADL");
11751
11752 // We don't perform ADL for implicit declarations of builtins.
11753 // Verify that this was correctly set up.
11754 FunctionDecl *F;
11755 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11756 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11757 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011758 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011759
John McCall57500772009-12-16 12:17:52 +000011760 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011761 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011762 }
John McCall57500772009-12-16 12:17:52 +000011763#endif
11764
John McCall4124c492011-10-17 18:40:02 +000011765 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011766 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011767 *Result = ExprError();
11768 return true;
11769 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011770
John McCall57500772009-12-16 12:17:52 +000011771 // Add the functions denoted by the callee to the set of candidate
11772 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011773 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011774
Hans Wennborgb2747382015-06-12 21:23:23 +000011775 if (getLangOpts().MSVCCompat &&
11776 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011777 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11778
11779 OverloadCandidateSet::iterator Best;
11780 if (CandidateSet->empty() ||
11781 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11782 OR_No_Viable_Function) {
11783 // In Microsoft mode, if we are inside a template class member function then
11784 // create a type dependent CallExpr. The goal is to postpone name lookup
11785 // to instantiation time to be able to search into type dependent base
11786 // classes.
11787 CallExpr *CE = new (Context) CallExpr(
11788 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011789 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011790 CE->setValueDependent(true);
11791 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011792 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011793 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011794 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011795 }
John McCalld681c392009-12-16 08:11:27 +000011796
Hans Wennborg64937c62015-06-11 21:21:57 +000011797 if (CandidateSet->empty())
11798 return false;
11799
John McCall4124c492011-10-17 18:40:02 +000011800 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011801 return false;
11802}
John McCall4124c492011-10-17 18:40:02 +000011803
Sam Panzer0f384432012-08-21 00:52:01 +000011804/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11805/// the completed call expression. If overload resolution fails, emits
11806/// diagnostics and returns ExprError()
11807static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11808 UnresolvedLookupExpr *ULE,
11809 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011810 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011811 SourceLocation RParenLoc,
11812 Expr *ExecConfig,
11813 OverloadCandidateSet *CandidateSet,
11814 OverloadCandidateSet::iterator *Best,
11815 OverloadingResult OverloadResult,
11816 bool AllowTypoCorrection) {
11817 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011818 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011819 RParenLoc, /*EmptyLookup=*/true,
11820 AllowTypoCorrection);
11821
11822 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011823 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011824 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011825 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011826 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11827 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011828 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011829 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11830 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011831 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011832
Richard Smith998a5912011-06-05 22:42:48 +000011833 case OR_No_Viable_Function: {
11834 // Try to recover by looking for viable functions which the user might
11835 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011836 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011837 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011838 /*EmptyLookup=*/false,
11839 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011840 if (!Recovery.isInvalid())
11841 return Recovery;
11842
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011843 // If the user passes in a function that we can't take the address of, we
11844 // generally end up emitting really bad error messages. Here, we attempt to
11845 // emit better ones.
11846 for (const Expr *Arg : Args) {
11847 if (!Arg->getType()->isFunctionType())
11848 continue;
11849 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11850 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11851 if (FD &&
11852 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11853 Arg->getExprLoc()))
11854 return ExprError();
11855 }
11856 }
11857
11858 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11859 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011860 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011861 break;
Richard Smith998a5912011-06-05 22:42:48 +000011862 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011863
11864 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011865 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011866 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011867 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011868 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011869
Sam Panzer0f384432012-08-21 00:52:01 +000011870 case OR_Deleted: {
11871 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11872 << (*Best)->Function->isDeleted()
11873 << ULE->getName()
11874 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11875 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011876 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011877
Sam Panzer0f384432012-08-21 00:52:01 +000011878 // We emitted an error for the unvailable/deleted function call but keep
11879 // the call in the AST.
11880 FunctionDecl *FDecl = (*Best)->Function;
11881 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011882 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11883 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011884 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011885 }
11886
Douglas Gregorb412e172010-07-25 18:17:45 +000011887 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011888 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011889}
11890
George Burgess IV7204ed92016-01-07 02:26:57 +000011891static void markUnaddressableCandidatesUnviable(Sema &S,
11892 OverloadCandidateSet &CS) {
11893 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11894 if (I->Viable &&
11895 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11896 I->Viable = false;
11897 I->FailureKind = ovl_fail_addr_not_available;
11898 }
11899 }
11900}
11901
Sam Panzer0f384432012-08-21 00:52:01 +000011902/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11903/// (which eventually refers to the declaration Func) and the call
11904/// arguments Args/NumArgs, attempt to resolve the function call down
11905/// to a specific function. If overload resolution succeeds, returns
11906/// the call expression produced by overload resolution.
11907/// Otherwise, emits diagnostics and returns ExprError.
11908ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11909 UnresolvedLookupExpr *ULE,
11910 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011911 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011912 SourceLocation RParenLoc,
11913 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011914 bool AllowTypoCorrection,
11915 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011916 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11917 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011918 ExprResult result;
11919
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011920 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11921 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011922 return result;
11923
George Burgess IV7204ed92016-01-07 02:26:57 +000011924 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11925 // functions that aren't addressible are considered unviable.
11926 if (CalleesAddressIsTaken)
11927 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11928
Sam Panzer0f384432012-08-21 00:52:01 +000011929 OverloadCandidateSet::iterator Best;
11930 OverloadingResult OverloadResult =
11931 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11932
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011933 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011934 RParenLoc, ExecConfig, &CandidateSet,
11935 &Best, OverloadResult,
11936 AllowTypoCorrection);
11937}
11938
John McCall4c4c1df2010-01-26 03:27:55 +000011939static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011940 return Functions.size() > 1 ||
11941 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11942}
11943
Douglas Gregor084d8552009-03-13 23:49:33 +000011944/// \brief Create a unary operation that may resolve to an overloaded
11945/// operator.
11946///
11947/// \param OpLoc The location of the operator itself (e.g., '*').
11948///
Craig Toppera92ffb02015-12-10 08:51:49 +000011949/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011950///
James Dennett18348b62012-06-22 08:52:37 +000011951/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011952/// considered by overload resolution. The caller needs to build this
11953/// set based on the context using, e.g.,
11954/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11955/// set should not contain any member functions; those will be added
11956/// by CreateOverloadedUnaryOp().
11957///
James Dennett91738ff2012-06-22 10:32:46 +000011958/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011959ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011960Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011961 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011962 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011963 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11964 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11965 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011966 // TODO: provide better source location info.
11967 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011968
John McCall4124c492011-10-17 18:40:02 +000011969 if (checkPlaceholderForOverload(*this, Input))
11970 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011971
Craig Topperc3ec1492014-05-26 06:22:03 +000011972 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011973 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011974
Douglas Gregor084d8552009-03-13 23:49:33 +000011975 // For post-increment and post-decrement, add the implicit '0' as
11976 // the second argument, so that we know this is a post-increment or
11977 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011978 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011979 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011980 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11981 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011982 NumArgs = 2;
11983 }
11984
Richard Smithe54c3072013-05-05 15:51:06 +000011985 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11986
Douglas Gregor084d8552009-03-13 23:49:33 +000011987 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011988 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011989 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11990 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011991
Craig Topperc3ec1492014-05-26 06:22:03 +000011992 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011993 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011994 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011995 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011996 /*ADL*/ true, IsOverloaded(Fns),
11997 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011998 return new (Context)
11999 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012000 VK_RValue, OpLoc, FPOptions());
Douglas Gregor084d8552009-03-13 23:49:33 +000012001 }
12002
12003 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012004 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000012005
12006 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012007 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012008
12009 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012010 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012011
John McCall4c4c1df2010-01-26 03:27:55 +000012012 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000012013 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000012014 /*ExplicitTemplateArgs*/nullptr,
12015 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000012016
Douglas Gregor084d8552009-03-13 23:49:33 +000012017 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012018 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000012019
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012020 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12021
Douglas Gregor084d8552009-03-13 23:49:33 +000012022 // Perform overload resolution.
12023 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012024 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000012025 case OR_Success: {
12026 // We found a built-in operator or an overloaded operator.
12027 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000012028
Douglas Gregor084d8552009-03-13 23:49:33 +000012029 if (FnDecl) {
12030 // We matched an overloaded operator. Build a call to that
12031 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000012032
Douglas Gregor084d8552009-03-13 23:49:33 +000012033 // Convert the arguments.
12034 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012035 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012036
John Wiegley01296292011-04-08 18:41:53 +000012037 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012038 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012039 Best->FoundDecl, Method);
12040 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012041 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012042 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012043 } else {
12044 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012045 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000012046 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012047 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000012048 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012049 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000012050 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000012051 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000012052 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012053 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012054 }
12055
Douglas Gregor084d8552009-03-13 23:49:33 +000012056 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000012057 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012058 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012059 if (FnExpr.isInvalid())
12060 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000012061
Richard Smithc1564702013-11-15 02:58:23 +000012062 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012063 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012064 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12065 ResultTy = ResultTy.getNonLValueExprType(Context);
12066
Eli Friedman030eee42009-11-18 03:58:17 +000012067 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000012068 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012069 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Adam Nemet484aa452017-03-27 19:17:25 +000012070 ResultTy, VK, OpLoc, FPOptions());
John McCall4fa0d5f2010-05-06 18:15:07 +000012071
Alp Toker314cc812014-01-25 16:55:45 +000012072 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000012073 return ExprError();
12074
George Burgess IVce6284b2017-01-28 02:19:40 +000012075 if (CheckFunctionCall(FnDecl, TheCall,
12076 FnDecl->getType()->castAs<FunctionProtoType>()))
12077 return ExprError();
12078
John McCallb268a282010-08-23 23:25:46 +000012079 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000012080 } else {
12081 // We matched a built-in operator. Convert the arguments, then
12082 // break out so that we will build the appropriate built-in
12083 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012084 ExprResult InputRes =
12085 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
12086 Best->Conversions[0], AA_Passing);
12087 if (InputRes.isInvalid())
12088 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012089 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000012090 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000012091 }
John Wiegley01296292011-04-08 18:41:53 +000012092 }
12093
12094 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000012095 // This is an erroneous use of an operator which can be overloaded by
12096 // a non-member function. Check for non-member operators which were
12097 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012098 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000012099 // FIXME: Recover by calling the found function.
12100 return ExprError();
12101
John Wiegley01296292011-04-08 18:41:53 +000012102 // No viable function; fall through to handling this as a
12103 // built-in operator, which will produce an error message for us.
12104 break;
12105
12106 case OR_Ambiguous:
12107 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12108 << UnaryOperator::getOpcodeStr(Opc)
12109 << Input->getType()
12110 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012111 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000012112 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12113 return ExprError();
12114
12115 case OR_Deleted:
12116 Diag(OpLoc, diag::err_ovl_deleted_oper)
12117 << Best->Function->isDeleted()
12118 << UnaryOperator::getOpcodeStr(Opc)
12119 << getDeletedOrUnavailableSuffix(Best->Function)
12120 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000012121 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012122 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012123 return ExprError();
12124 }
Douglas Gregor084d8552009-03-13 23:49:33 +000012125
12126 // Either we found no viable overloaded operator or we matched a
12127 // built-in operator. In either case, fall through to trying to
12128 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000012129 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000012130}
12131
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012132/// \brief Create a binary operation that may resolve to an overloaded
12133/// operator.
12134///
12135/// \param OpLoc The location of the operator itself (e.g., '+').
12136///
Craig Toppera92ffb02015-12-10 08:51:49 +000012137/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012138///
James Dennett18348b62012-06-22 08:52:37 +000012139/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012140/// considered by overload resolution. The caller needs to build this
12141/// set based on the context using, e.g.,
12142/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12143/// set should not contain any member functions; those will be added
12144/// by CreateOverloadedBinOp().
12145///
12146/// \param LHS Left-hand argument.
12147/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000012148ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012149Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000012150 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000012151 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012152 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012153 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000012154 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012155
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012156 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12157 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12158
12159 // If either side is type-dependent, create an appropriate dependent
12160 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000012161 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000012162 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012163 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000012164 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000012165 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012166 return new (Context) BinaryOperator(
12167 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +000012168 OpLoc, FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012169
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012170 return new (Context) CompoundAssignOperator(
12171 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12172 Context.DependentTy, Context.DependentTy, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012173 FPFeatures);
Douglas Gregor5287f092009-11-05 00:51:44 +000012174 }
John McCall4c4c1df2010-01-26 03:27:55 +000012175
12176 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000012177 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012178 // TODO: provide better source location info in DNLoc component.
12179 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000012180 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000012181 = UnresolvedLookupExpr::Create(Context, NamingClass,
12182 NestedNameSpecifierLoc(), OpNameInfo,
12183 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012184 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012185 return new (Context)
12186 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
Adam Nemet484aa452017-03-27 19:17:25 +000012187 VK_RValue, OpLoc, FPFeatures);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012188 }
12189
John McCall4124c492011-10-17 18:40:02 +000012190 // Always do placeholder-like conversions on the RHS.
12191 if (checkPlaceholderForOverload(*this, Args[1]))
12192 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012193
John McCall526ab472011-10-25 17:37:35 +000012194 // Do placeholder-like conversion on the LHS; note that we should
12195 // not get here with a PseudoObject LHS.
12196 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000012197 if (checkPlaceholderForOverload(*this, Args[0]))
12198 return ExprError();
12199
Sebastian Redl6a96bf72009-11-18 23:10:33 +000012200 // If this is the assignment operator, we only perform overload resolution
12201 // if the left-hand side is a class or enumeration type. This is actually
12202 // a hack. The standard requires that we do overload resolution between the
12203 // various built-in candidates, but as DR507 points out, this can lead to
12204 // problems. So we do it this way, which pretty much follows what GCC does.
12205 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000012206 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000012207 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012208
John McCalle26a8722010-12-04 08:14:53 +000012209 // If this is the .* operator, which is not overloadable, just
12210 // create a built-in binary operator.
12211 if (Opc == BO_PtrMemD)
12212 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12213
Douglas Gregor084d8552009-03-13 23:49:33 +000012214 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012215 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012216
12217 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012218 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012219
12220 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012221 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012222
Richard Smith0daabd72014-09-23 20:31:39 +000012223 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12224 // performed for an assignment operator (nor for operator[] nor operator->,
12225 // which don't get here).
12226 if (Opc != BO_Assign)
12227 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12228 /*ExplicitTemplateArgs*/ nullptr,
12229 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000012230
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012231 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012232 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012233
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012234 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12235
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012236 // Perform overload resolution.
12237 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012238 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000012239 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012240 // We found a built-in operator or an overloaded operator.
12241 FunctionDecl *FnDecl = Best->Function;
12242
12243 if (FnDecl) {
12244 // We matched an overloaded operator. Build a call to that
12245 // operator.
12246
12247 // Convert the arguments.
12248 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000012249 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000012250 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000012251
Chandler Carruth8e543b32010-12-12 08:17:55 +000012252 ExprResult Arg1 =
12253 PerformCopyInitialization(
12254 InitializedEntity::InitializeParameter(Context,
12255 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012256 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012257 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012258 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012259
John Wiegley01296292011-04-08 18:41:53 +000012260 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012261 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012262 Best->FoundDecl, Method);
12263 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012264 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012265 Args[0] = Arg0.getAs<Expr>();
12266 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012267 } else {
12268 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000012269 ExprResult Arg0 = PerformCopyInitialization(
12270 InitializedEntity::InitializeParameter(Context,
12271 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012272 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012273 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012274 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012275
Chandler Carruth8e543b32010-12-12 08:17:55 +000012276 ExprResult Arg1 =
12277 PerformCopyInitialization(
12278 InitializedEntity::InitializeParameter(Context,
12279 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012280 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000012281 if (Arg1.isInvalid())
12282 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012283 Args[0] = LHS = Arg0.getAs<Expr>();
12284 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012285 }
12286
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012287 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012288 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012289 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012290 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012291 if (FnExpr.isInvalid())
12292 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012293
Richard Smithc1564702013-11-15 02:58:23 +000012294 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000012295 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012296 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12297 ResultTy = ResultTy.getNonLValueExprType(Context);
12298
John McCallb268a282010-08-23 23:25:46 +000012299 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012300 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012301 Args, ResultTy, VK, OpLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012302 FPFeatures);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012303
Alp Toker314cc812014-01-25 16:55:45 +000012304 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012305 FnDecl))
12306 return ExprError();
12307
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012308 ArrayRef<const Expr *> ArgsArray(Args, 2);
George Burgess IVce6284b2017-01-28 02:19:40 +000012309 const Expr *ImplicitThis = nullptr;
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012310 // Cut off the implicit 'this'.
George Burgess IVce6284b2017-01-28 02:19:40 +000012311 if (isa<CXXMethodDecl>(FnDecl)) {
12312 ImplicitThis = ArgsArray[0];
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012313 ArgsArray = ArgsArray.slice(1);
George Burgess IVce6284b2017-01-28 02:19:40 +000012314 }
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012315
12316 // Check for a self move.
12317 if (Op == OO_Equal)
12318 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12319
George Burgess IVce6284b2017-01-28 02:19:40 +000012320 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12321 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12322 VariadicDoesNotApply);
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000012323
John McCallb268a282010-08-23 23:25:46 +000012324 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012325 } else {
12326 // We matched a built-in operator. Convert the arguments, then
12327 // break out so that we will build the appropriate built-in
12328 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012329 ExprResult ArgsRes0 =
12330 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12331 Best->Conversions[0], AA_Passing);
12332 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012333 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012334 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012335
John Wiegley01296292011-04-08 18:41:53 +000012336 ExprResult ArgsRes1 =
12337 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12338 Best->Conversions[1], AA_Passing);
12339 if (ArgsRes1.isInvalid())
12340 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012341 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012342 break;
12343 }
12344 }
12345
Douglas Gregor66950a32009-09-30 21:46:01 +000012346 case OR_No_Viable_Function: {
12347 // C++ [over.match.oper]p9:
12348 // If the operator is the operator , [...] and there are no
12349 // viable functions, then the operator is assumed to be the
12350 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000012351 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000012352 break;
12353
Chandler Carruth8e543b32010-12-12 08:17:55 +000012354 // For class as left operand for assignment or compound assigment
12355 // operator do not fall through to handling in built-in, but report that
12356 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000012357 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012358 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000012359 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000012360 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12361 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000012362 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000012363 if (Args[0]->getType()->isIncompleteType()) {
12364 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12365 << Args[0]->getType()
12366 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12367 }
Douglas Gregor66950a32009-09-30 21:46:01 +000012368 } else {
Richard Smith998a5912011-06-05 22:42:48 +000012369 // This is an erroneous use of an operator which can be overloaded by
12370 // a non-member function. Check for non-member operators which were
12371 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012372 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000012373 // FIXME: Recover by calling the found function.
12374 return ExprError();
12375
Douglas Gregor66950a32009-09-30 21:46:01 +000012376 // No viable function; try to create a built-in operation, which will
12377 // produce an error. Then, show the non-viable candidates.
12378 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000012379 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012380 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000012381 "C++ binary operator overloading is missing candidates!");
12382 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012383 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012384 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012385 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000012386 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012387
12388 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012389 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012390 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000012391 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000012392 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012393 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012394 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012395 return ExprError();
12396
12397 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000012398 if (isImplicitlyDeleted(Best->Function)) {
12399 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12400 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000012401 << Context.getRecordType(Method->getParent())
12402 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012403
Richard Smithde1a4872012-12-28 12:23:24 +000012404 // The user probably meant to call this special member. Just
12405 // explain why it's deleted.
12406 NoteDeletedFunction(Method);
12407 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012408 } else {
12409 Diag(OpLoc, diag::err_ovl_deleted_oper)
12410 << Best->Function->isDeleted()
12411 << BinaryOperator::getOpcodeStr(Opc)
12412 << getDeletedOrUnavailableSuffix(Best->Function)
12413 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12414 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012415 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012416 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012417 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012418 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012419
Douglas Gregor66950a32009-09-30 21:46:01 +000012420 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012421 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012422}
12423
John McCalldadc5752010-08-24 06:29:42 +000012424ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012425Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12426 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012427 Expr *Base, Expr *Idx) {
12428 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012429 DeclarationName OpName =
12430 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12431
12432 // If either side is type-dependent, create an appropriate dependent
12433 // expression.
12434 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12435
Craig Topperc3ec1492014-05-26 06:22:03 +000012436 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012437 // CHECKME: no 'operator' keyword?
12438 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12439 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012440 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012441 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012442 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012443 /*ADL*/ true, /*Overloaded*/ false,
12444 UnresolvedSetIterator(),
12445 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012446 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012447
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012448 return new (Context)
12449 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
Adam Nemet484aa452017-03-27 19:17:25 +000012450 Context.DependentTy, VK_RValue, RLoc, FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012451 }
12452
John McCall4124c492011-10-17 18:40:02 +000012453 // Handle placeholders on both operands.
12454 if (checkPlaceholderForOverload(*this, Args[0]))
12455 return ExprError();
12456 if (checkPlaceholderForOverload(*this, Args[1]))
12457 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012458
Sebastian Redladba46e2009-10-29 20:17:01 +000012459 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012460 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012461
12462 // Subscript can only be overloaded as a member function.
12463
12464 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012465 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012466
12467 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012468 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012469
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012470 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12471
Sebastian Redladba46e2009-10-29 20:17:01 +000012472 // Perform overload resolution.
12473 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012474 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012475 case OR_Success: {
12476 // We found a built-in operator or an overloaded operator.
12477 FunctionDecl *FnDecl = Best->Function;
12478
12479 if (FnDecl) {
12480 // We matched an overloaded operator. Build a call to that
12481 // operator.
12482
John McCalla0296f72010-03-19 07:35:19 +000012483 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012484
Sebastian Redladba46e2009-10-29 20:17:01 +000012485 // Convert the arguments.
12486 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012487 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012488 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012489 Best->FoundDecl, Method);
12490 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012491 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012492 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012493
Anders Carlssona68e51e2010-01-29 18:37:50 +000012494 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012495 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012496 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012497 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012498 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012499 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012500 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012501 if (InputInit.isInvalid())
12502 return ExprError();
12503
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012504 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012505
Sebastian Redladba46e2009-10-29 20:17:01 +000012506 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012507 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12508 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012509 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012510 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012511 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012512 OpLocInfo.getLoc(),
12513 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012514 if (FnExpr.isInvalid())
12515 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012516
Richard Smithc1564702013-11-15 02:58:23 +000012517 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012518 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012519 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12520 ResultTy = ResultTy.getNonLValueExprType(Context);
12521
John McCallb268a282010-08-23 23:25:46 +000012522 CXXOperatorCallExpr *TheCall =
12523 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012524 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012525 ResultTy, VK, RLoc,
Adam Nemet484aa452017-03-27 19:17:25 +000012526 FPOptions());
Sebastian Redladba46e2009-10-29 20:17:01 +000012527
Alp Toker314cc812014-01-25 16:55:45 +000012528 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012529 return ExprError();
12530
George Burgess IVce6284b2017-01-28 02:19:40 +000012531 if (CheckFunctionCall(Method, TheCall,
12532 Method->getType()->castAs<FunctionProtoType>()))
12533 return ExprError();
12534
John McCallb268a282010-08-23 23:25:46 +000012535 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012536 } else {
12537 // We matched a built-in operator. Convert the arguments, then
12538 // break out so that we will build the appropriate built-in
12539 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012540 ExprResult ArgsRes0 =
12541 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12542 Best->Conversions[0], AA_Passing);
12543 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012544 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012545 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012546
12547 ExprResult ArgsRes1 =
12548 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12549 Best->Conversions[1], AA_Passing);
12550 if (ArgsRes1.isInvalid())
12551 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012552 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012553
12554 break;
12555 }
12556 }
12557
12558 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012559 if (CandidateSet.empty())
12560 Diag(LLoc, diag::err_ovl_no_oper)
12561 << Args[0]->getType() << /*subscript*/ 0
12562 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12563 else
12564 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12565 << Args[0]->getType()
12566 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012567 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012568 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012569 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012570 }
12571
12572 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012573 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012574 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012575 << Args[0]->getType() << Args[1]->getType()
12576 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012577 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012578 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012579 return ExprError();
12580
12581 case OR_Deleted:
12582 Diag(LLoc, diag::err_ovl_deleted_oper)
12583 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012584 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012585 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012586 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012587 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012588 return ExprError();
12589 }
12590
12591 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012592 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012593}
12594
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012595/// BuildCallToMemberFunction - Build a call to a member
12596/// function. MemExpr is the expression that refers to the member
12597/// function (and includes the object parameter), Args/NumArgs are the
12598/// arguments to the function call (not including the object
12599/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012600/// expression refers to a non-static member function or an overloaded
12601/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012602ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012603Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012604 SourceLocation LParenLoc,
12605 MultiExprArg Args,
12606 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012607 assert(MemExprE->getType() == Context.BoundMemberTy ||
12608 MemExprE->getType() == Context.OverloadTy);
12609
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012610 // Dig out the member expression. This holds both the object
12611 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012612 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012613
John McCall0009fcc2011-04-26 20:42:42 +000012614 // Determine whether this is a call to a pointer-to-member function.
12615 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12616 assert(op->getType() == Context.BoundMemberTy);
12617 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12618
12619 QualType fnType =
12620 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12621
12622 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12623 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012624 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012625
12626 // Check that the object type isn't more qualified than the
12627 // member function we're calling.
12628 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12629
12630 QualType objectType = op->getLHS()->getType();
12631 if (op->getOpcode() == BO_PtrMemI)
12632 objectType = objectType->castAs<PointerType>()->getPointeeType();
12633 Qualifiers objectQuals = objectType.getQualifiers();
12634
12635 Qualifiers difference = objectQuals - funcQuals;
12636 difference.removeObjCGCAttr();
12637 difference.removeAddressSpace();
12638 if (difference) {
12639 std::string qualsString = difference.getAsString();
12640 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12641 << fnType.getUnqualifiedType()
12642 << qualsString
12643 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12644 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012645
John McCall0009fcc2011-04-26 20:42:42 +000012646 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012647 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012648 resultType, valueKind, RParenLoc);
12649
Alp Toker314cc812014-01-25 16:55:45 +000012650 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012651 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012652 return ExprError();
12653
Craig Topperc3ec1492014-05-26 06:22:03 +000012654 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012655 return ExprError();
12656
Richard Trieu9be9c682013-06-22 02:30:38 +000012657 if (CheckOtherCall(call, proto))
12658 return ExprError();
12659
John McCall0009fcc2011-04-26 20:42:42 +000012660 return MaybeBindToTemporary(call);
12661 }
12662
David Majnemerced8bdf2015-02-25 17:36:15 +000012663 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12664 return new (Context)
12665 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12666
John McCall4124c492011-10-17 18:40:02 +000012667 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012668 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012669 return ExprError();
12670
John McCall10eae182009-11-30 22:42:35 +000012671 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012672 CXXMethodDecl *Method = nullptr;
12673 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12674 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012675 if (isa<MemberExpr>(NakedMemExpr)) {
12676 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012677 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012678 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012679 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012680 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012681 } else {
12682 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012683 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012684
John McCall6e9f8f62009-12-03 04:06:58 +000012685 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012686 Expr::Classification ObjectClassification
12687 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12688 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012689
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012690 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012691 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12692 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012693
John McCall2d74de92009-12-01 22:10:20 +000012694 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012695 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012696 if (UnresExpr->hasExplicitTemplateArgs()) {
12697 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12698 TemplateArgs = &TemplateArgsBuffer;
12699 }
12700
John McCall10eae182009-11-30 22:42:35 +000012701 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12702 E = UnresExpr->decls_end(); I != E; ++I) {
12703
John McCall6e9f8f62009-12-03 04:06:58 +000012704 NamedDecl *Func = *I;
12705 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12706 if (isa<UsingShadowDecl>(Func))
12707 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12708
Douglas Gregor02824322011-01-26 19:30:28 +000012709
Francois Pichet64225792011-01-18 05:04:39 +000012710 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012711 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012712 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012713 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012714 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012715 // If explicit template arguments were provided, we can't call a
12716 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012717 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012718 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012719
John McCalla0296f72010-03-19 07:35:19 +000012720 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
George Burgess IVce6284b2017-01-28 02:19:40 +000012721 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012722 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012723 } else {
George Burgess IV177399e2017-01-09 04:12:14 +000012724 AddMethodTemplateCandidate(
12725 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
George Burgess IVce6284b2017-01-28 02:19:40 +000012726 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
George Burgess IV177399e2017-01-09 04:12:14 +000012727 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012728 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012729 }
Mike Stump11289f42009-09-09 15:08:12 +000012730
John McCall10eae182009-11-30 22:42:35 +000012731 DeclarationName DeclName = UnresExpr->getMemberName();
12732
John McCall4124c492011-10-17 18:40:02 +000012733 UnbridgedCasts.restore();
12734
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012735 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012736 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012737 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012738 case OR_Success:
12739 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012740 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012741 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012742 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12743 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012744 // If FoundDecl is different from Method (such as if one is a template
12745 // and the other a specialization), make sure DiagnoseUseOfDecl is
12746 // called on both.
12747 // FIXME: This would be more comprehensively addressed by modifying
12748 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12749 // being used.
12750 if (Method != FoundDecl.getDecl() &&
12751 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12752 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012753 break;
12754
12755 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012756 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012757 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012758 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012759 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012760 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012761 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012762
12763 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012764 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012765 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012766 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012767 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012768 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012769
12770 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012771 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012772 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012773 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012774 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012775 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012776 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012777 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012778 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012779 }
12780
John McCall16df1e52010-03-30 21:47:33 +000012781 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012782
John McCall2d74de92009-12-01 22:10:20 +000012783 // If overload resolution picked a static member, build a
12784 // non-member call based on that function.
12785 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012786 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12787 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012788 }
12789
John McCall10eae182009-11-30 22:42:35 +000012790 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012791 }
12792
Alp Toker314cc812014-01-25 16:55:45 +000012793 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012794 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12795 ResultType = ResultType.getNonLValueExprType(Context);
12796
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012797 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012798 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012799 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012800 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012801
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012802 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012803 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012804 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012805 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012806
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012807 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012808 // We only need to do this if there was actually an overload; otherwise
12809 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012810 if (!Method->isStatic()) {
12811 ExprResult ObjectArg =
12812 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12813 FoundDecl, Method);
12814 if (ObjectArg.isInvalid())
12815 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012816 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012817 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012818
12819 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012820 const FunctionProtoType *Proto =
12821 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012822 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012823 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012824 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012825
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012826 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012827
Richard Smith55ce3522012-06-25 20:30:08 +000012828 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012829 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012830
George Burgess IVaea6ade2015-09-25 17:53:16 +000012831 // In the case the method to call was not selected by the overloading
12832 // resolution process, we still need to handle the enable_if attribute. Do
George Burgess IV0d546532016-11-10 21:47:12 +000012833 // that here, so it will not hide previous -- and more relevant -- errors.
George Burgess IVadd6ab52016-11-16 21:31:25 +000012834 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
George Burgess IVaea6ade2015-09-25 17:53:16 +000012835 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
George Burgess IVadd6ab52016-11-16 21:31:25 +000012836 Diag(MemE->getMemberLoc(),
George Burgess IVaea6ade2015-09-25 17:53:16 +000012837 diag::err_ovl_no_viable_member_function_in_call)
12838 << Method << Method->getSourceRange();
12839 Diag(Method->getLocation(),
George Burgess IV177399e2017-01-09 04:12:14 +000012840 diag::note_ovl_candidate_disabled_by_function_cond_attr)
George Burgess IVaea6ade2015-09-25 17:53:16 +000012841 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12842 return ExprError();
12843 }
12844 }
12845
Anders Carlsson47061ee2011-05-06 14:25:31 +000012846 if ((isa<CXXConstructorDecl>(CurContext) ||
12847 isa<CXXDestructorDecl>(CurContext)) &&
12848 TheCall->getMethodDecl()->isPure()) {
12849 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12850
Davide Italianoccb37382015-07-14 23:36:10 +000012851 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12852 MemExpr->performsVirtualDispatch(getLangOpts())) {
12853 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012854 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12855 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12856 << MD->getParent()->getDeclName();
12857
12858 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012859 if (getLangOpts().AppleKext)
12860 Diag(MemExpr->getLocStart(),
12861 diag::note_pure_qualified_call_kext)
12862 << MD->getParent()->getDeclName()
12863 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012864 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012865 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012866
12867 if (CXXDestructorDecl *DD =
12868 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12869 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012870 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012871 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12872 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12873 MemExpr->getMemberLoc());
12874 }
12875
John McCallb268a282010-08-23 23:25:46 +000012876 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012877}
12878
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012879/// BuildCallToObjectOfClassType - Build a call to an object of class
12880/// type (C++ [over.call.object]), which can end up invoking an
12881/// overloaded function call operator (@c operator()) or performing a
12882/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012883ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012884Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012885 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012886 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012887 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012888 if (checkPlaceholderForOverload(*this, Obj))
12889 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012890 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012891
12892 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012893 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012894 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012895
Nico Weberb58e51c2014-11-19 05:21:39 +000012896 assert(Object.get()->getType()->isRecordType() &&
12897 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012898 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012899
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012900 // C++ [over.call.object]p1:
12901 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012902 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012903 // candidate functions includes at least the function call
12904 // operators of T. The function call operators of T are obtained by
12905 // ordinary lookup of the name operator() in the context of
12906 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012907 OverloadCandidateSet CandidateSet(LParenLoc,
12908 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012909 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012910
John Wiegley01296292011-04-08 18:41:53 +000012911 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012912 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012913 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012914
John McCall27b18f82009-11-17 02:14:36 +000012915 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12916 LookupQualifiedName(R, Record->getDecl());
12917 R.suppressDiagnostics();
12918
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012919 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012920 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012921 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
George Burgess IVce6284b2017-01-28 02:19:40 +000012922 Object.get()->Classify(Context), Args, CandidateSet,
12923 /*SuppressUserConversions=*/false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012924 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012925
Douglas Gregorab7897a2008-11-19 22:57:39 +000012926 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012927 // In addition, for each (non-explicit in C++0x) conversion function
12928 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012929 //
12930 // operator conversion-type-id () cv-qualifier;
12931 //
12932 // where cv-qualifier is the same cv-qualification as, or a
12933 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012934 // denotes the type "pointer to function of (P1,...,Pn) returning
12935 // R", or the type "reference to pointer to function of
12936 // (P1,...,Pn) returning R", or the type "reference to function
12937 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012938 // is also considered as a candidate function. Similarly,
12939 // surrogate call functions are added to the set of candidate
12940 // functions for each conversion function declared in an
12941 // accessible base class provided the function is not hidden
12942 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012943 const auto &Conversions =
12944 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12945 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012946 NamedDecl *D = *I;
12947 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12948 if (isa<UsingShadowDecl>(D))
12949 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012950
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012951 // Skip over templated conversion functions; they aren't
12952 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012953 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012954 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012955
John McCall6e9f8f62009-12-03 04:06:58 +000012956 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012957 if (!Conv->isExplicit()) {
12958 // Strip the reference type (if any) and then the pointer type (if
12959 // any) to get down to what might be a function type.
12960 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12961 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12962 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012963
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012964 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12965 {
12966 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012967 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012968 }
12969 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012970 }
Mike Stump11289f42009-09-09 15:08:12 +000012971
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012972 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12973
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012974 // Perform overload resolution.
12975 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012976 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012977 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012978 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012979 // Overload resolution succeeded; we'll build the appropriate call
12980 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012981 break;
12982
12983 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012984 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012985 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012986 << Object.get()->getType() << /*call*/ 1
12987 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012988 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012989 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012990 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012991 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012992 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012993 break;
12994
12995 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012996 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012997 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012998 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012999 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013000 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000013001
13002 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013003 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000013004 diag::err_ovl_deleted_object_call)
13005 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000013006 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013007 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000013008 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013009 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000013010 break;
Mike Stump11289f42009-09-09 15:08:12 +000013011 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013012
Douglas Gregorb412e172010-07-25 18:17:45 +000013013 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013014 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013015
John McCall4124c492011-10-17 18:40:02 +000013016 UnbridgedCasts.restore();
13017
Craig Topperc3ec1492014-05-26 06:22:03 +000013018 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000013019 // Since there is no function declaration, this is one of the
13020 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000013021 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000013022 = cast<CXXConversionDecl>(
13023 Best->Conversions[0].UserDefined.ConversionFunction);
13024
Craig Topperc3ec1492014-05-26 06:22:03 +000013025 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13026 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000013027 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13028 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000013029 assert(Conv == Best->FoundDecl.getDecl() &&
13030 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000013031 // We selected one of the surrogate functions that converts the
13032 // object parameter to a function pointer. Perform the conversion
13033 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013034
Fariborz Jahanian774cf792009-09-28 18:35:46 +000013035 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000013036 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013037 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13038 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000013039 if (Call.isInvalid())
13040 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000013041 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013042 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13043 CK_UserDefinedConversion, Call.get(),
13044 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013045
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013046 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000013047 }
13048
Craig Topperc3ec1492014-05-26 06:22:03 +000013049 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000013050
Douglas Gregorab7897a2008-11-19 22:57:39 +000013051 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13052 // that calls this method, using Object for the implicit object
13053 // parameter and passing along the remaining arguments.
13054 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000013055
13056 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000013057 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000013058 return ExprError();
13059
Chandler Carruth8e543b32010-12-12 08:17:55 +000013060 const FunctionProtoType *Proto =
13061 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013062
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013063 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000013064
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013065 DeclarationNameInfo OpLocInfo(
13066 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13067 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000013068 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013069 HadMultipleCandidates,
13070 OpLocInfo.getLoc(),
13071 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000013072 if (NewFn.isInvalid())
13073 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013074
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013075 // Build the full argument list for the method call (the implicit object
13076 // parameter is placed at the beginning of the list).
George Burgess IV215f6e72016-12-13 19:22:56 +000013077 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013078 MethodArgs[0] = Object.get();
George Burgess IV215f6e72016-12-13 19:22:56 +000013079 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013080
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013081 // Once we've built TheCall, all of the expressions are properly
13082 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000013083 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013084 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13085 ResultTy = ResultTy.getNonLValueExprType(Context);
13086
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000013087 CXXOperatorCallExpr *TheCall = new (Context)
George Burgess IV215f6e72016-12-13 19:22:56 +000013088 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
Adam Nemet484aa452017-03-27 19:17:25 +000013089 VK, RParenLoc, FPOptions());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013090
Alp Toker314cc812014-01-25 16:55:45 +000013091 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000013092 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013093
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013094 // We may have default arguments. If so, we need to allocate more
13095 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013096 if (Args.size() < NumParams)
13097 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013098
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013099 bool IsError = false;
13100
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013101 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000013102 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000013103 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013104 Best->FoundDecl, Method);
13105 if (ObjRes.isInvalid())
13106 IsError = true;
13107 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013108 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013109 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013110
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013111 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013112 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013113 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013114 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013115 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000013116
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013117 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013118
John McCalldadc5752010-08-24 06:29:42 +000013119 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013120 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000013121 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013122 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000013123 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013124
Anders Carlsson7c5fe482010-01-29 18:43:53 +000013125 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013126 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013127 } else {
John McCalldadc5752010-08-24 06:29:42 +000013128 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000013129 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13130 if (DefArg.isInvalid()) {
13131 IsError = true;
13132 break;
13133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013134
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013135 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000013136 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013137
13138 TheCall->setArg(i + 1, Arg);
13139 }
13140
13141 // If this is a variadic call, handle args passed through "...".
13142 if (Proto->isVariadic()) {
13143 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000013144 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013145 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13146 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000013147 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013148 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013149 }
13150 }
13151
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000013152 if (IsError) return true;
13153
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000013154 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000013155
Richard Smith55ce3522012-06-25 20:30:08 +000013156 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000013157 return true;
13158
John McCalle172be52010-08-24 06:09:16 +000013159 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000013160}
13161
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013162/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000013163/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013164/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000013165ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013166Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13167 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000013168 assert(Base->getType()->isRecordType() &&
13169 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000013170
John McCall4124c492011-10-17 18:40:02 +000013171 if (checkPlaceholderForOverload(*this, Base))
13172 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000013173
John McCallbc077cf2010-02-08 23:07:23 +000013174 SourceLocation Loc = Base->getExprLoc();
13175
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013176 // C++ [over.ref]p1:
13177 //
13178 // [...] An expression x->m is interpreted as (x.operator->())->m
13179 // for a class object x of type T if T::operator->() exists and if
13180 // the operator is selected as the best match function by the
13181 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000013182 DeclarationName OpName =
13183 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000013184 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013185 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000013186
John McCallbc077cf2010-02-08 23:07:23 +000013187 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013188 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000013189 return ExprError();
13190
John McCall27b18f82009-11-17 02:14:36 +000013191 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13192 LookupQualifiedName(R, BaseRecord->getDecl());
13193 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000013194
13195 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000013196 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000013197 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
George Burgess IVce6284b2017-01-28 02:19:40 +000013198 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000013199 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013200
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013201 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13202
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013203 // Perform overload resolution.
13204 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000013205 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013206 case OR_Success:
13207 // Overload resolution succeeded; we'll build the call below.
13208 break;
13209
13210 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013211 if (CandidateSet.empty()) {
13212 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000013213 if (NoArrowOperatorFound) {
13214 // Report this specific error to the caller instead of emitting a
13215 // diagnostic, as requested.
13216 *NoArrowOperatorFound = true;
13217 return ExprError();
13218 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013219 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13220 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013221 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000013222 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013223 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000013224 }
13225 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013226 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000013227 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013228 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013229 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013230
13231 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000013232 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13233 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013234 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013235 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000013236
13237 case OR_Deleted:
13238 Diag(OpLoc, diag::err_ovl_deleted_oper)
13239 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013240 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000013241 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000013242 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000013243 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000013244 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013245 }
13246
Craig Topperc3ec1492014-05-26 06:22:03 +000013247 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000013248
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013249 // Convert the object parameter.
13250 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000013251 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000013252 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000013253 Best->FoundDecl, Method);
13254 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000013255 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013256 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000013257
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013258 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000013259 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000013260 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000013261 if (FnExpr.isInvalid())
13262 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013263
Alp Toker314cc812014-01-25 16:55:45 +000013264 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000013265 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13266 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000013267 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013268 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Adam Nemet484aa452017-03-27 19:17:25 +000013269 Base, ResultTy, VK, OpLoc, FPOptions());
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000013270
Alp Toker314cc812014-01-25 16:55:45 +000013271 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
George Burgess IVce6284b2017-01-28 02:19:40 +000013272 return ExprError();
13273
13274 if (CheckFunctionCall(Method, TheCall,
13275 Method->getType()->castAs<FunctionProtoType>()))
13276 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000013277
13278 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000013279}
13280
Richard Smithbcc22fc2012-03-09 08:00:36 +000013281/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13282/// a literal operator described by the provided lookup results.
13283ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13284 DeclarationNameInfo &SuffixInfo,
13285 ArrayRef<Expr*> Args,
13286 SourceLocation LitEndLoc,
13287 TemplateArgumentListInfo *TemplateArgs) {
13288 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000013289
Richard Smith100b24a2014-04-17 01:52:14 +000013290 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13291 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000013292 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13293 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000013294
Richard Smithbcc22fc2012-03-09 08:00:36 +000013295 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13296
Richard Smithbcc22fc2012-03-09 08:00:36 +000013297 // Perform overload resolution. This will usually be trivial, but might need
13298 // to perform substitutions for a literal operator template.
13299 OverloadCandidateSet::iterator Best;
13300 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13301 case OR_Success:
13302 case OR_Deleted:
13303 break;
13304
13305 case OR_No_Viable_Function:
13306 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13307 << R.getLookupName();
13308 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13309 return ExprError();
13310
13311 case OR_Ambiguous:
13312 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13313 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13314 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000013315 }
13316
Richard Smithbcc22fc2012-03-09 08:00:36 +000013317 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000013318 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13319 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000013320 SuffixInfo.getLoc(),
13321 SuffixInfo.getInfo());
13322 if (Fn.isInvalid())
13323 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000013324
13325 // Check the argument types. This should almost always be a no-op, except
13326 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000013327 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000013328 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000013329 ExprResult InputInit = PerformCopyInitialization(
13330 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13331 SourceLocation(), Args[ArgIdx]);
13332 if (InputInit.isInvalid())
13333 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013334 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000013335 }
13336
Alp Toker314cc812014-01-25 16:55:45 +000013337 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000013338 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13339 ResultTy = ResultTy.getNonLValueExprType(Context);
13340
Richard Smithc67fdd42012-03-07 08:35:16 +000013341 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013342 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000013343 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000013344 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13345
Alp Toker314cc812014-01-25 16:55:45 +000013346 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000013347 return ExprError();
13348
Craig Topperc3ec1492014-05-26 06:22:03 +000013349 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000013350 return ExprError();
13351
13352 return MaybeBindToTemporary(UDL);
13353}
13354
Sam Panzer0f384432012-08-21 00:52:01 +000013355/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13356/// given LookupResult is non-empty, it is assumed to describe a member which
13357/// will be invoked. Otherwise, the function will be found via argument
13358/// dependent lookup.
13359/// CallExpr is set to a valid expression and FRS_Success returned on success,
13360/// otherwise CallExpr is set to ExprError() and some non-success value
13361/// is returned.
13362Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000013363Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13364 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000013365 const DeclarationNameInfo &NameInfo,
13366 LookupResult &MemberLookup,
13367 OverloadCandidateSet *CandidateSet,
13368 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000013369 Scope *S = nullptr;
13370
Sam Panzer0f384432012-08-21 00:52:01 +000013371 CandidateSet->clear();
13372 if (!MemberLookup.empty()) {
13373 ExprResult MemberRef =
13374 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13375 /*IsPtr=*/false, CXXScopeSpec(),
13376 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013377 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013378 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000013379 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000013380 if (MemberRef.isInvalid()) {
13381 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013382 return FRS_DiagnosticIssued;
13383 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013384 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000013385 if (CallExpr->isInvalid()) {
13386 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013387 return FRS_DiagnosticIssued;
13388 }
13389 } else {
13390 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000013391 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000013392 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000013393 NestedNameSpecifierLoc(), NameInfo,
13394 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000013395 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000013396
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013397 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000013398 CandidateSet, CallExpr);
13399 if (CandidateSet->empty() || CandidateSetError) {
13400 *CallExpr = ExprError();
13401 return FRS_NoViableFunction;
13402 }
13403 OverloadCandidateSet::iterator Best;
13404 OverloadingResult OverloadResult =
13405 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13406
13407 if (OverloadResult == OR_No_Viable_Function) {
13408 *CallExpr = ExprError();
13409 return FRS_NoViableFunction;
13410 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013411 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013412 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013413 OverloadResult,
13414 /*AllowTypoCorrection=*/false);
13415 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13416 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013417 return FRS_DiagnosticIssued;
13418 }
13419 }
13420 return FRS_Success;
13421}
13422
13423
Douglas Gregorcd695e52008-11-10 20:40:00 +000013424/// FixOverloadedFunctionReference - E is an expression that refers to
13425/// a C++ overloaded function (possibly with some parentheses and
13426/// perhaps a '&' around it). We have resolved the overloaded function
13427/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013428/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013429Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013430 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013431 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013432 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13433 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013434 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013435 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013436
Douglas Gregor51c538b2009-11-20 19:42:02 +000013437 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013438 }
13439
Douglas Gregor51c538b2009-11-20 19:42:02 +000013440 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013441 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13442 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013443 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013444 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013445 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013446 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013447 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013448 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013449
13450 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013451 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013452 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013453 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013454 }
13455
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013456 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13457 if (!GSE->isResultDependent()) {
13458 Expr *SubExpr =
13459 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13460 if (SubExpr == GSE->getResultExpr())
13461 return GSE;
13462
13463 // Replace the resulting type information before rebuilding the generic
13464 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013465 ArrayRef<Expr *> A = GSE->getAssocExprs();
13466 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013467 unsigned ResultIdx = GSE->getResultIndex();
13468 AssocExprs[ResultIdx] = SubExpr;
13469
13470 return new (Context) GenericSelectionExpr(
13471 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13472 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13473 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13474 ResultIdx);
13475 }
13476 // Rather than fall through to the unreachable, return the original generic
13477 // selection expression.
13478 return GSE;
13479 }
13480
Douglas Gregor51c538b2009-11-20 19:42:02 +000013481 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013482 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013483 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013484 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13485 if (Method->isStatic()) {
13486 // Do nothing: static member functions aren't any different
13487 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013488 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013489 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013490 // UnresolvedLookupExpr holding an overloaded member function
13491 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013492 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13493 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013494 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013495 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013496
John McCalld14a8642009-11-21 08:51:07 +000013497 assert(isa<DeclRefExpr>(SubExpr)
13498 && "fixed to something other than a decl ref");
13499 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13500 && "fixed to a member ref with no nested name qualifier");
13501
13502 // We have taken the address of a pointer to member
13503 // function. Perform the computation here so that we get the
13504 // appropriate pointer to member type.
13505 QualType ClassType
13506 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13507 QualType MemPtrType
13508 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013509 // Under the MS ABI, lock down the inheritance model now.
13510 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13511 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013512
John McCall7decc9e2010-11-18 06:31:45 +000013513 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13514 VK_RValue, OK_Ordinary,
13515 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013516 }
13517 }
John McCall16df1e52010-03-30 21:47:33 +000013518 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13519 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013520 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013521 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013522
John McCalle3027922010-08-25 11:45:40 +000013523 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013524 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013525 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013526 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013527 }
John McCalld14a8642009-11-21 08:51:07 +000013528
Richard Smith84a0b6d2016-10-18 23:39:12 +000013529 // C++ [except.spec]p17:
13530 // An exception-specification is considered to be needed when:
13531 // - in an expression the function is the unique lookup result or the
13532 // selected member of a set of overloaded functions
13533 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13534 ResolveExceptionSpec(E->getExprLoc(), FPT);
13535
John McCalld14a8642009-11-21 08:51:07 +000013536 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013537 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013538 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013539 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013540 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13541 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013542 }
13543
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013544 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13545 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013546 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013547 Fn,
John McCall113bee02012-03-10 09:33:50 +000013548 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013549 ULE->getNameLoc(),
13550 Fn->getType(),
13551 VK_LValue,
13552 Found.getDecl(),
13553 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013554 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013555 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13556 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013557 }
13558
John McCall10eae182009-11-30 22:42:35 +000013559 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013560 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013561 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013562 if (MemExpr->hasExplicitTemplateArgs()) {
13563 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13564 TemplateArgs = &TemplateArgsBuffer;
13565 }
John McCall6b51f282009-11-23 01:53:49 +000013566
John McCall2d74de92009-12-01 22:10:20 +000013567 Expr *Base;
13568
John McCall7decc9e2010-11-18 06:31:45 +000013569 // If we're filling in a static method where we used to have an
13570 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013571 if (MemExpr->isImplicitAccess()) {
13572 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013573 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13574 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013575 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013576 Fn,
John McCall113bee02012-03-10 09:33:50 +000013577 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013578 MemExpr->getMemberLoc(),
13579 Fn->getType(),
13580 VK_LValue,
13581 Found.getDecl(),
13582 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013583 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013584 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13585 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013586 } else {
13587 SourceLocation Loc = MemExpr->getMemberLoc();
13588 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013589 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013590 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013591 Base = new (Context) CXXThisExpr(Loc,
13592 MemExpr->getBaseType(),
13593 /*isImplicit=*/true);
13594 }
John McCall2d74de92009-12-01 22:10:20 +000013595 } else
John McCallc3007a22010-10-26 07:05:15 +000013596 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013597
John McCall4adb38c2011-04-27 00:36:17 +000013598 ExprValueKind valueKind;
13599 QualType type;
13600 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13601 valueKind = VK_LValue;
13602 type = Fn->getType();
13603 } else {
13604 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013605 type = Context.BoundMemberTy;
13606 }
13607
13608 MemberExpr *ME = MemberExpr::Create(
13609 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13610 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13611 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13612 OK_Ordinary);
13613 ME->setHadMultipleCandidates(true);
13614 MarkMemberReferenced(ME);
13615 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013617
John McCallc3007a22010-10-26 07:05:15 +000013618 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013619}
13620
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013621ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013622 DeclAccessPair Found,
13623 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013624 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013625}