blob: 10aa997745951dd2e7e7479e0a904c3763e305cc [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035#include <algorithm>
David Blaikie8ad22e62014-05-01 23:01:41 +000036#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000037
Richard Smith17c00b42014-11-12 01:24:00 +000038using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000039using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000040
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000041static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
George Burgess IV21081362016-07-24 23:12:40 +000042 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43 return P->hasAttr<PassObjectSizeAttr>();
44 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000045}
46
Nick Lewycky134af912013-02-07 05:08:22 +000047/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000048static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000049CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000051 SourceLocation Loc = SourceLocation(),
52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000053 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000054 return ExprError();
55 // If FoundDecl is different from Fn (such as if one is a template
56 // and the other a specialization), make sure DiagnoseUseOfDecl is
57 // called on both.
58 // FIXME: This would be more comprehensively addressed by modifying
59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60 // being used.
61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000062 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000063 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000064 VK_LValue, Loc, LocInfo);
65 if (HadMultipleCandidates)
66 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000067
68 S.MarkDeclRefReferenced(DRE);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000069 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
70 CK_FunctionToPointerDecay);
John McCall7decc9e2010-11-18 06:31:45 +000071}
72
John McCall5c32be02010-08-24 20:38:10 +000073static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
74 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000075 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000076 bool CStyle,
77 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000078
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000079static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
80 QualType &ToType,
81 bool InOverloadResolution,
82 StandardConversionSequence &SCS,
83 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000084static OverloadingResult
85IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
86 UserDefinedConversionSequence& User,
87 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000088 bool AllowExplicit,
89 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000090
91
92static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +000093CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +000094 const StandardConversionSequence& SCS1,
95 const StandardConversionSequence& SCS2);
96
97static ImplicitConversionSequence::CompareKind
98CompareQualificationConversions(Sema &S,
99 const StandardConversionSequence& SCS1,
100 const StandardConversionSequence& SCS2);
101
102static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +0000103CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +0000104 const StandardConversionSequence& SCS1,
105 const StandardConversionSequence& SCS2);
106
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000107/// GetConversionRank - Retrieve the implicit conversion rank
108/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000109ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000110 static const ImplicitConversionRank
111 Rank[(int)ICK_Num_Conversion_Kinds] = {
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
115 ICR_Exact_Match,
116 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000117 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000118 ICR_Promotion,
119 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000120 ICR_Promotion,
121 ICR_Conversion,
122 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
127 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000128 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000129 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000130 ICR_Conversion,
131 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000132 ICR_Complex_Real_Conversion,
133 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000134 ICR_Conversion,
George Burgess IV45461812015-10-11 20:13:20 +0000135 ICR_Writeback_Conversion,
136 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
137 // it was omitted by the patch that added
138 // ICK_Zero_Event_Conversion
George Burgess IV2099b542016-09-02 22:59:57 +0000139 ICR_C_Conversion,
140 ICR_C_Conversion_Extension
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000141 };
142 return Rank[(int)Kind];
143}
144
145/// GetImplicitConversionName - Return the name of this kind of
146/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000147static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000148 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000149 "No conversion",
150 "Lvalue-to-rvalue",
151 "Array-to-pointer",
152 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000153 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000154 "Qualification",
155 "Integral promotion",
156 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000157 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000158 "Integral conversion",
159 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000160 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000161 "Floating-integral conversion",
162 "Pointer conversion",
163 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000164 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000165 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000166 "Derived-to-base conversion",
167 "Vector conversion",
168 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000169 "Complex-real conversion",
170 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000171 "Transparent Union Conversion",
George Burgess IV45461812015-10-11 20:13:20 +0000172 "Writeback conversion",
173 "OpenCL Zero Event Conversion",
George Burgess IV2099b542016-09-02 22:59:57 +0000174 "C specific type conversion",
175 "Incompatible pointer conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000176 };
177 return Name[Kind];
178}
179
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000180/// StandardConversionSequence - Set the standard conversion
181/// sequence to the identity conversion.
182void StandardConversionSequence::setAsIdentityConversion() {
183 First = ICK_Identity;
184 Second = ICK_Identity;
185 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000186 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000187 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000188 ReferenceBinding = false;
189 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000190 IsLvalueReference = true;
191 BindsToFunctionLvalue = false;
192 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000193 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000194 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000195 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000196}
197
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000198/// getRank - Retrieve the rank of this standard conversion sequence
199/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
200/// implicit conversions.
201ImplicitConversionRank StandardConversionSequence::getRank() const {
202 ImplicitConversionRank Rank = ICR_Exact_Match;
203 if (GetConversionRank(First) > Rank)
204 Rank = GetConversionRank(First);
205 if (GetConversionRank(Second) > Rank)
206 Rank = GetConversionRank(Second);
207 if (GetConversionRank(Third) > Rank)
208 Rank = GetConversionRank(Third);
209 return Rank;
210}
211
212/// isPointerConversionToBool - Determines whether this conversion is
213/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000214/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000215/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000216bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000217 // Note that FromType has not necessarily been transformed by the
218 // array-to-pointer or function-to-pointer implicit conversions, so
219 // check for their presence as well as checking whether FromType is
220 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000221 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000222 (getFromType()->isPointerType() ||
223 getFromType()->isObjCObjectPointerType() ||
224 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000225 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000226 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
227 return true;
228
229 return false;
230}
231
Douglas Gregor5c407d92008-10-23 00:40:37 +0000232/// isPointerConversionToVoidPointer - Determines whether this
233/// conversion is a conversion of a pointer to a void pointer. This is
234/// used as part of the ranking of standard conversion sequences (C++
235/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000236bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000237StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000238isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000239 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000240 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000241
242 // Note that FromType has not necessarily been transformed by the
243 // array-to-pointer implicit conversion, so check for its presence
244 // and redo the conversion to get a pointer.
245 if (First == ICK_Array_To_Pointer)
246 FromType = Context.getArrayDecayedType(FromType);
247
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000248 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000249 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000250 return ToPtrType->getPointeeType()->isVoidType();
251
252 return false;
253}
254
Richard Smith66e05fe2012-01-18 05:21:49 +0000255/// Skip any implicit casts which could be either part of a narrowing conversion
256/// or after one in an implicit conversion.
257static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
258 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
259 switch (ICE->getCastKind()) {
260 case CK_NoOp:
261 case CK_IntegralCast:
262 case CK_IntegralToBoolean:
263 case CK_IntegralToFloating:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000264 case CK_BooleanToSignedIntegral:
Richard Smith66e05fe2012-01-18 05:21:49 +0000265 case CK_FloatingToIntegral:
266 case CK_FloatingToBoolean:
267 case CK_FloatingCast:
268 Converted = ICE->getSubExpr();
269 continue;
270
271 default:
272 return Converted;
273 }
274 }
275
276 return Converted;
277}
278
279/// Check if this standard conversion sequence represents a narrowing
280/// conversion, according to C++11 [dcl.init.list]p7.
281///
282/// \param Ctx The AST context.
283/// \param Converted The result of applying this standard conversion sequence.
284/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
285/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000286/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
287/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000288NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000289StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
290 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000291 APValue &ConstantValue,
292 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000293 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000294
295 // C++11 [dcl.init.list]p7:
296 // A narrowing conversion is an implicit conversion ...
297 QualType FromType = getToType(0);
298 QualType ToType = getToType(1);
Richard Smithed638862016-03-28 06:08:37 +0000299
300 // A conversion to an enumeration type is narrowing if the conversion to
301 // the underlying type is narrowing. This only arises for expressions of
302 // the form 'Enum{init}'.
303 if (auto *ET = ToType->getAs<EnumType>())
304 ToType = ET->getDecl()->getIntegerType();
305
Richard Smith66e05fe2012-01-18 05:21:49 +0000306 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000307 // 'bool' is an integral type; dispatch to the right place to handle it.
308 case ICK_Boolean_Conversion:
309 if (FromType->isRealFloatingType())
310 goto FloatingIntegralConversion;
311 if (FromType->isIntegralOrUnscopedEnumerationType())
312 goto IntegralConversion;
313 // Boolean conversions can be from pointers and pointers to members
314 // [conv.bool], and those aren't considered narrowing conversions.
315 return NK_Not_Narrowing;
316
Richard Smith66e05fe2012-01-18 05:21:49 +0000317 // -- from a floating-point type to an integer type, or
318 //
319 // -- from an integer type or unscoped enumeration type to a floating-point
320 // type, except where the source is a constant expression and the actual
321 // value after conversion will fit into the target type and will produce
322 // the original value when converted back to the original type, or
323 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000324 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000325 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
326 return NK_Type_Narrowing;
327 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
328 llvm::APSInt IntConstantValue;
329 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
330 if (Initializer &&
331 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
332 // Convert the integer to the floating type.
333 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
334 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
335 llvm::APFloat::rmNearestTiesToEven);
336 // And back.
337 llvm::APSInt ConvertedValue = IntConstantValue;
338 bool ignored;
339 Result.convertToInteger(ConvertedValue,
340 llvm::APFloat::rmTowardZero, &ignored);
341 // If the resulting value is different, this was a narrowing conversion.
342 if (IntConstantValue != ConvertedValue) {
343 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000344 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000345 return NK_Constant_Narrowing;
346 }
347 } else {
348 // Variables are always narrowings.
349 return NK_Variable_Narrowing;
350 }
351 }
352 return NK_Not_Narrowing;
353
354 // -- from long double to double or float, or from double to float, except
355 // where the source is a constant expression and the actual value after
356 // conversion is within the range of values that can be represented (even
357 // if it cannot be represented exactly), or
358 case ICK_Floating_Conversion:
359 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
360 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
361 // FromType is larger than ToType.
362 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
363 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
364 // Constant!
365 assert(ConstantValue.isFloat());
366 llvm::APFloat FloatVal = ConstantValue.getFloat();
367 // Convert the source value into the target type.
368 bool ignored;
369 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
370 Ctx.getFloatTypeSemantics(ToType),
371 llvm::APFloat::rmNearestTiesToEven, &ignored);
372 // If there was no overflow, the source value is within the range of
373 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000374 if (ConvertStatus & llvm::APFloat::opOverflow) {
375 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000376 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000377 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000378 } else {
379 return NK_Variable_Narrowing;
380 }
381 }
382 return NK_Not_Narrowing;
383
384 // -- from an integer type or unscoped enumeration type to an integer type
385 // that cannot represent all the values of the original type, except where
386 // the source is a constant expression and the actual value after
387 // conversion will fit into the target type and will produce the original
388 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000389 case ICK_Integral_Conversion:
390 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000391 assert(FromType->isIntegralOrUnscopedEnumerationType());
392 assert(ToType->isIntegralOrUnscopedEnumerationType());
393 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
394 const unsigned FromWidth = Ctx.getIntWidth(FromType);
395 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
396 const unsigned ToWidth = Ctx.getIntWidth(ToType);
397
398 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000399 (FromWidth == ToWidth && FromSigned != ToSigned) ||
400 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000401 // Not all values of FromType can be represented in ToType.
402 llvm::APSInt InitializerValue;
403 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000404 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
405 // Such conversions on variables are always narrowing.
406 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000407 }
408 bool Narrowing = false;
409 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000410 // Negative -> unsigned is narrowing. Otherwise, more bits is never
411 // narrowing.
412 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000413 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000414 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000415 // Add a bit to the InitializerValue so we don't have to worry about
416 // signed vs. unsigned comparisons.
417 InitializerValue = InitializerValue.extend(
418 InitializerValue.getBitWidth() + 1);
419 // Convert the initializer to and from the target width and signed-ness.
420 llvm::APSInt ConvertedValue = InitializerValue;
421 ConvertedValue = ConvertedValue.trunc(ToWidth);
422 ConvertedValue.setIsSigned(ToSigned);
423 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
424 ConvertedValue.setIsSigned(InitializerValue.isSigned());
425 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000426 if (ConvertedValue != InitializerValue)
427 Narrowing = true;
428 }
429 if (Narrowing) {
430 ConstantType = Initializer->getType();
431 ConstantValue = APValue(InitializerValue);
432 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000433 }
434 }
435 return NK_Not_Narrowing;
436 }
437
438 default:
439 // Other kinds of conversions are not narrowings.
440 return NK_Not_Narrowing;
441 }
442}
443
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000444/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000445/// error. Useful for debugging overloading issues.
Yaron Kerencdae9412016-01-29 19:38:18 +0000446LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000447 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000448 bool PrintedSomething = false;
449 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000450 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000451 PrintedSomething = true;
452 }
453
454 if (Second != ICK_Identity) {
455 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000456 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000458 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000459
460 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000461 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000462 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000463 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000464 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000465 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000466 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000467 PrintedSomething = true;
468 }
469
470 if (Third != ICK_Identity) {
471 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000473 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000474 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000475 PrintedSomething = true;
476 }
477
478 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000479 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 }
481}
482
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000483/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000485void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000486 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000488 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000489 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000491 if (ConversionFunction)
492 OS << '\'' << *ConversionFunction << '\'';
493 else
494 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000496 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000497 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 }
499}
500
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000501/// dump - Print this implicit 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 ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000504 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000505 if (isStdInitializerListElement())
506 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 switch (ConversionKind) {
508 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000509 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000510 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000511 break;
512 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000513 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000514 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000515 break;
516 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000517 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000518 break;
John McCall0d1da222010-01-12 00:44:57 +0000519 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000520 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000521 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000522 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000523 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524 break;
525 }
526
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000527 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528}
529
John McCall0d1da222010-01-12 00:44:57 +0000530void AmbiguousConversionSequence::construct() {
531 new (&conversions()) ConversionSet();
532}
533
534void AmbiguousConversionSequence::destruct() {
535 conversions().~ConversionSet();
536}
537
538void
539AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
540 FromTypePtr = O.FromTypePtr;
541 ToTypePtr = O.ToTypePtr;
542 new (&conversions()) ConversionSet(O.conversions());
543}
544
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000545namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000546 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000547 // template argument information.
548 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000549 TemplateArgument FirstArg;
550 TemplateArgument SecondArg;
551 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000552 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000553 // template parameter and template argument information.
554 struct DFIParamWithArguments : DFIArguments {
555 TemplateParameter Param;
556 };
Richard Smith9b534542015-12-31 02:02:54 +0000557 // Structure used by DeductionFailureInfo to store template argument
558 // information and the index of the problematic call argument.
559 struct DFIDeducedMismatchArgs : DFIArguments {
560 TemplateArgumentList *TemplateArgs;
561 unsigned CallArgIndex;
562 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000563}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000565/// \brief Convert from Sema's representation of template deduction information
566/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000567DeductionFailureInfo
568clang::MakeDeductionFailureInfo(ASTContext &Context,
569 Sema::TemplateDeductionResult TDK,
570 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000571 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000572 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000573 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 switch (TDK) {
575 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000576 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000577 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000578 case Sema::TDK_TooManyArguments:
579 case Sema::TDK_TooFewArguments:
Richard Smith9b534542015-12-31 02:02:54 +0000580 case Sema::TDK_MiscellaneousDeductionFailure:
581 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000582 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000584 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000585 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000586 Result.Data = Info.Param.getOpaqueValue();
587 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000588
Richard Smith9b534542015-12-31 02:02:54 +0000589 case Sema::TDK_DeducedMismatch: {
590 // FIXME: Should allocate from normal heap so that we can free this later.
591 auto *Saved = new (Context) DFIDeducedMismatchArgs;
592 Saved->FirstArg = Info.FirstArg;
593 Saved->SecondArg = Info.SecondArg;
594 Saved->TemplateArgs = Info.take();
595 Saved->CallArgIndex = Info.CallArgIndex;
596 Result.Data = Saved;
597 break;
598 }
599
Richard Smith44ecdbd2013-01-31 05:19:49 +0000600 case Sema::TDK_NonDeducedMismatch: {
601 // FIXME: Should allocate from normal heap so that we can free this later.
602 DFIArguments *Saved = new (Context) DFIArguments;
603 Saved->FirstArg = Info.FirstArg;
604 Saved->SecondArg = Info.SecondArg;
605 Result.Data = Saved;
606 break;
607 }
608
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000610 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000611 // FIXME: Should allocate from normal heap so that we can free this later.
612 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000613 Saved->Param = Info.Param;
614 Saved->FirstArg = Info.FirstArg;
615 Saved->SecondArg = Info.SecondArg;
616 Result.Data = Saved;
617 break;
618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000620 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000621 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000622 if (Info.hasSFINAEDiagnostic()) {
623 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
624 SourceLocation(), PartialDiagnostic::NullDiagnostic());
625 Info.takeSFINAEDiagnostic(*Diag);
626 Result.HasDiagnostic = true;
627 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000628 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000629
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000630 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000631 Result.Data = Info.Expression;
632 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000635 return Result;
636}
John McCall0d1da222010-01-12 00:44:57 +0000637
Larisse Voufo98b20f12013-07-19 23:00:19 +0000638void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000639 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
640 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000641 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000642 case Sema::TDK_InstantiationDepth:
643 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000644 case Sema::TDK_TooManyArguments:
645 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000646 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000647 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000648 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000649
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000650 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000651 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000652 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000653 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000654 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000655 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000656 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000657
658 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000659 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000660 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000661 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
662 Diag->~PartialDiagnosticAt();
663 HasDiagnostic = false;
664 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000665 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666
Douglas Gregor461761d2010-05-08 18:20:53 +0000667 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000668 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000669 break;
670 }
671}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672
Larisse Voufo98b20f12013-07-19 23:00:19 +0000673PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000674 if (HasDiagnostic)
675 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000676 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000677}
678
Larisse Voufo98b20f12013-07-19 23:00:19 +0000679TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000680 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
681 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000682 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000683 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000684 case Sema::TDK_TooManyArguments:
685 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000686 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +0000687 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000688 case Sema::TDK_NonDeducedMismatch:
689 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000690 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000692 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000693 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000694 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000695
696 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000697 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000698 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000700 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000701 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000702 break;
703 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000705 return TemplateParameter();
706}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000707
Larisse Voufo98b20f12013-07-19 23:00:19 +0000708TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000709 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000710 case Sema::TDK_Success:
711 case Sema::TDK_Invalid:
712 case Sema::TDK_InstantiationDepth:
713 case Sema::TDK_TooManyArguments:
714 case Sema::TDK_TooFewArguments:
715 case Sema::TDK_Incomplete:
716 case Sema::TDK_InvalidExplicitArguments:
717 case Sema::TDK_Inconsistent:
718 case Sema::TDK_Underqualified:
719 case Sema::TDK_NonDeducedMismatch:
720 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000721 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000722
Richard Smith9b534542015-12-31 02:02:54 +0000723 case Sema::TDK_DeducedMismatch:
724 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
725
Richard Smith44ecdbd2013-01-31 05:19:49 +0000726 case Sema::TDK_SubstitutionFailure:
727 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
Richard Smith44ecdbd2013-01-31 05:19:49 +0000729 // Unhandled
730 case Sema::TDK_MiscellaneousDeductionFailure:
731 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000732 }
733
Craig Topperc3ec1492014-05-26 06:22:03 +0000734 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000735}
736
Larisse Voufo98b20f12013-07-19 23:00:19 +0000737const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
739 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000740 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000741 case Sema::TDK_InstantiationDepth:
742 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000743 case Sema::TDK_TooManyArguments:
744 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000745 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000746 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000747 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000748 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000749
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000750 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000751 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000752 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000753 case Sema::TDK_NonDeducedMismatch:
754 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000755
Douglas Gregor461761d2010-05-08 18:20:53 +0000756 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000757 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000758 break;
759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000760
Craig Topperc3ec1492014-05-26 06:22:03 +0000761 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000763
Larisse Voufo98b20f12013-07-19 23:00:19 +0000764const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000765 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
766 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000767 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000768 case Sema::TDK_InstantiationDepth:
769 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000770 case Sema::TDK_TooManyArguments:
771 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000772 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000773 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000774 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000775 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000776
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000777 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000778 case Sema::TDK_Underqualified:
Richard Smith9b534542015-12-31 02:02:54 +0000779 case Sema::TDK_DeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000780 case Sema::TDK_NonDeducedMismatch:
781 return &static_cast<DFIArguments*>(Data)->SecondArg;
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;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000789}
790
Larisse Voufo98b20f12013-07-19 23:00:19 +0000791Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000792 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
793 Sema::TDK_FailedOverloadResolution)
794 return static_cast<Expr*>(Data);
795
Craig Topperc3ec1492014-05-26 06:22:03 +0000796 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000797}
798
Richard Smith9b534542015-12-31 02:02:54 +0000799llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
800 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
801 Sema::TDK_DeducedMismatch)
802 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
803
804 return llvm::None;
805}
806
Benjamin Kramer97e59492012-10-09 15:52:25 +0000807void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000808 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000809 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
810 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000811 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
812 i->DeductionFailure.Destroy();
813 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000814}
815
816void OverloadCandidateSet::clear() {
817 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000818 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000819 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000820 Functions.clear();
821}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822
John McCall4124c492011-10-17 18:40:02 +0000823namespace {
824 class UnbridgedCastsSet {
825 struct Entry {
826 Expr **Addr;
827 Expr *Saved;
828 };
829 SmallVector<Entry, 2> Entries;
830
831 public:
832 void save(Sema &S, Expr *&E) {
833 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
834 Entry entry = { &E, E };
835 Entries.push_back(entry);
836 E = S.stripARCUnbridgedCast(E);
837 }
838
839 void restore() {
840 for (SmallVectorImpl<Entry>::iterator
841 i = Entries.begin(), e = Entries.end(); i != e; ++i)
842 *i->Addr = i->Saved;
843 }
844 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000845}
John McCall4124c492011-10-17 18:40:02 +0000846
847/// checkPlaceholderForOverload - Do any interesting placeholder-like
848/// preprocessing on the given expression.
849///
850/// \param unbridgedCasts a collection to which to add unbridged casts;
851/// without this, they will be immediately diagnosed as errors
852///
853/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000854static bool
855checkPlaceholderForOverload(Sema &S, Expr *&E,
856 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000857 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
858 // We can't handle overloaded expressions here because overload
859 // resolution might reasonably tweak them.
860 if (placeholder->getKind() == BuiltinType::Overload) return false;
861
862 // If the context potentially accepts unbridged ARC casts, strip
863 // the unbridged cast and add it to the collection for later restoration.
864 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
865 unbridgedCasts) {
866 unbridgedCasts->save(S, E);
867 return false;
868 }
869
870 // Go ahead and check everything else.
871 ExprResult result = S.CheckPlaceholderExpr(E);
872 if (result.isInvalid())
873 return true;
874
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000875 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000876 return false;
877 }
878
879 // Nothing to do.
880 return false;
881}
882
883/// checkArgPlaceholdersForOverload - Check a set of call operands for
884/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000885static bool checkArgPlaceholdersForOverload(Sema &S,
886 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000887 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000888 for (unsigned i = 0, e = Args.size(); i != e; ++i)
889 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000890 return true;
891
892 return false;
893}
894
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000895// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000896// overload of the declarations in Old. This routine returns false if
897// New and Old cannot be overloaded, e.g., if New has the same
898// signature as some function in Old (C++ 1.3.10) or if the Old
899// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000900// it does return false, MatchedDecl will point to the decl that New
901// cannot be overloaded with. This decl may be a UsingShadowDecl on
902// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000903//
904// Example: Given the following input:
905//
906// void f(int, float); // #1
907// void f(int, int); // #2
908// int f(int, int); // #3
909//
910// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000911// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000912//
John McCall3d988d92009-12-02 08:47:38 +0000913// When we process #2, Old contains only the FunctionDecl for #1. By
914// comparing the parameter types, we see that #1 and #2 are overloaded
915// (since they have different signatures), so this routine returns
916// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000917//
John McCall3d988d92009-12-02 08:47:38 +0000918// When we process #3, Old is an overload set containing #1 and #2. We
919// compare the signatures of #3 to #1 (they're overloaded, so we do
920// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
921// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000922// signature), IsOverload returns false and MatchedDecl will be set to
923// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000924//
925// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
926// into a class by a using declaration. The rules for whether to hide
927// shadow declarations ignore some properties which otherwise figure
928// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000929Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000930Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
931 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000932 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000933 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000934 NamedDecl *OldD = *I;
935
936 bool OldIsUsingDecl = false;
937 if (isa<UsingShadowDecl>(OldD)) {
938 OldIsUsingDecl = true;
939
940 // We can always introduce two using declarations into the same
941 // context, even if they have identical signatures.
942 if (NewIsUsingDecl) continue;
943
944 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
945 }
946
Richard Smithf091e122015-09-15 01:28:55 +0000947 // A using-declaration does not conflict with another declaration
948 // if one of them is hidden.
949 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
950 continue;
951
John McCalle9cccd82010-06-16 08:42:20 +0000952 // If either declaration was introduced by a using declaration,
953 // we'll need to use slightly different rules for matching.
954 // Essentially, these rules are the normal rules, except that
955 // function templates hide function templates with different
956 // return types or template parameter lists.
957 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000958 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
959 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000960
Alp Tokera2794f92014-01-22 07:29:52 +0000961 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000962 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
963 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
964 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
965 continue;
966 }
967
Alp Tokera2794f92014-01-22 07:29:52 +0000968 if (!isa<FunctionTemplateDecl>(OldD) &&
969 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000970 continue;
971
John McCalldaa3d6b2009-12-09 03:35:25 +0000972 Match = *I;
973 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000974 }
John McCalla8987a2942010-11-10 03:01:53 +0000975 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000976 // We can overload with these, which can show up when doing
977 // redeclaration checks for UsingDecls.
978 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000979 } else if (isa<TagDecl>(OldD)) {
980 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000981 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
982 // Optimistically assume that an unresolved using decl will
983 // overload; if it doesn't, we'll have to diagnose during
984 // template instantiation.
985 } else {
John McCall1f82f242009-11-18 22:49:29 +0000986 // (C++ 13p1):
987 // Only function declarations can be overloaded; object and type
988 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000989 Match = *I;
990 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000991 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000992 }
John McCall1f82f242009-11-18 22:49:29 +0000993
John McCalldaa3d6b2009-12-09 03:35:25 +0000994 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000995}
996
Richard Smithac974a32013-06-30 09:48:50 +0000997bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
Justin Lebarba122ab2016-03-30 23:30:21 +0000998 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
Richard Smithac974a32013-06-30 09:48:50 +0000999 // C++ [basic.start.main]p2: This function shall not be overloaded.
1000 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +00001001 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +00001002
David Majnemerc729b0b2013-09-16 22:44:20 +00001003 // MSVCRT user defined entry points cannot be overloaded.
1004 if (New->isMSVCRTEntryPoint())
1005 return false;
1006
John McCall1f82f242009-11-18 22:49:29 +00001007 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1008 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1009
1010 // C++ [temp.fct]p2:
1011 // A function template can be overloaded with other function templates
1012 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +00001013 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +00001014 return true;
1015
1016 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +00001017 QualType OldQType = Context.getCanonicalType(Old->getType());
1018 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001019
1020 // Compare the signatures (C++ 1.3.10) of the two functions to
1021 // determine whether they are overloads. If we find any mismatch
1022 // in the signature, they are overloads.
1023
1024 // If either of these functions is a K&R-style function (no
1025 // prototype), then we consider them to have matching signatures.
1026 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1027 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1028 return false;
1029
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001030 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1031 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001032
1033 // The signature of a function includes the types of its
1034 // parameters (C++ 1.3.10), which includes the presence or absence
1035 // of the ellipsis; see C++ DR 357).
1036 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001037 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001038 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001039 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001040 return true;
1041
1042 // C++ [temp.over.link]p4:
1043 // The signature of a function template consists of its function
1044 // signature, its return type and its template parameter list. The names
1045 // of the template parameters are significant only for establishing the
1046 // relationship between the template parameters and the rest of the
1047 // signature.
1048 //
1049 // We check the return type and template parameter lists for function
1050 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001051 //
1052 // However, we don't consider either of these when deciding whether
1053 // a member introduced by a shadow declaration is hidden.
Justin Lebar39fd5292016-03-30 20:41:05 +00001054 if (!UseMemberUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001055 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1056 OldTemplate->getTemplateParameters(),
1057 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001058 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001059 return true;
1060
1061 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001062 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001063 //
1064 // As part of this, also check whether one of the member functions
1065 // is static, in which case they are not overloads (C++
1066 // 13.1p2). While not part of the definition of the signature,
1067 // this check is important to determine whether these functions
1068 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001069 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1070 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001071 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001072 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1073 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
Justin Lebar39fd5292016-03-30 20:41:05 +00001074 if (!UseMemberUsingDeclRules &&
Richard Smith574f4f62013-01-14 05:37:29 +00001075 (OldMethod->getRefQualifier() == RQ_None ||
1076 NewMethod->getRefQualifier() == RQ_None)) {
1077 // C++0x [over.load]p2:
1078 // - Member function declarations with the same name and the same
1079 // parameter-type-list as well as member function template
1080 // declarations with the same name, the same parameter-type-list, and
1081 // the same template parameter lists cannot be overloaded if any of
1082 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001083 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001084 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001085 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001086 }
1087 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001089
Richard Smith574f4f62013-01-14 05:37:29 +00001090 // We may not have applied the implicit const for a constexpr member
1091 // function yet (because we haven't yet resolved whether this is a static
1092 // or non-static member function). Add it now, on the assumption that this
1093 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001094 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001095 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001096 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001097 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001098 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001099
1100 // We do not allow overloading based off of '__restrict'.
1101 OldQuals &= ~Qualifiers::Restrict;
1102 NewQuals &= ~Qualifiers::Restrict;
1103 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001104 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001106
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001107 // Though pass_object_size is placed on parameters and takes an argument, we
1108 // consider it to be a function-level modifier for the sake of function
1109 // identity. Either the function has one or more parameters with
1110 // pass_object_size or it doesn't.
1111 if (functionHasPassObjectSizeParams(New) !=
1112 functionHasPassObjectSizeParams(Old))
1113 return true;
1114
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001115 // enable_if attributes are an order-sensitive part of the signature.
1116 for (specific_attr_iterator<EnableIfAttr>
1117 NewI = New->specific_attr_begin<EnableIfAttr>(),
1118 NewE = New->specific_attr_end<EnableIfAttr>(),
1119 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1120 OldE = Old->specific_attr_end<EnableIfAttr>();
1121 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1122 if (NewI == NewE || OldI == OldE)
1123 return true;
1124 llvm::FoldingSetNodeID NewID, OldID;
1125 NewI->getCond()->Profile(NewID, Context, true);
1126 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001127 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001128 return true;
1129 }
1130
Justin Lebarba122ab2016-03-30 23:30:21 +00001131 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
Artem Belevich94a55e82015-09-22 17:22:59 +00001132 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1133 OldTarget = IdentifyCUDATarget(Old);
1134 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1135 return false;
1136
1137 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1138
1139 // Don't allow mixing of HD with other kinds. This guarantees that
1140 // we have only one viable function with this signature on any
1141 // side of CUDA compilation .
Artem Belevich1ef9b592016-02-24 21:54:45 +00001142 // __global__ functions can't be overloaded based on attribute
1143 // difference because, like HD, they also exist on both sides.
1144 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1145 (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
Artem Belevich94a55e82015-09-22 17:22:59 +00001146 return false;
1147
1148 // Allow overloading of functions with same signature, but
1149 // different CUDA target attributes.
1150 return NewTarget != OldTarget;
1151 }
1152
John McCall1f82f242009-11-18 22:49:29 +00001153 // The signatures match; this is not an overload.
1154 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001155}
1156
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001157/// \brief Checks availability of the function depending on the current
1158/// function context. Inside an unavailable function, unavailability is ignored.
1159///
1160/// \returns true if \arg FD is unavailable and current context is inside
1161/// an available function, false otherwise.
1162bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
Duncan P. N. Exon Smith85363922016-03-08 10:28:52 +00001163 if (!FD->isUnavailable())
1164 return false;
1165
1166 // Walk up the context of the caller.
1167 Decl *C = cast<Decl>(CurContext);
1168 do {
1169 if (C->isUnavailable())
1170 return false;
1171 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1172 return true;
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001173}
1174
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001175/// \brief Tries a user-defined conversion from From to ToType.
1176///
1177/// Produces an implicit conversion sequence for when a standard conversion
1178/// is not an option. See TryImplicitConversion for more information.
1179static ImplicitConversionSequence
1180TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1181 bool SuppressUserConversions,
1182 bool AllowExplicit,
1183 bool InOverloadResolution,
1184 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001185 bool AllowObjCWritebackConversion,
1186 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001187 ImplicitConversionSequence ICS;
1188
1189 if (SuppressUserConversions) {
1190 // We're not in the case above, so there is no conversion that
1191 // we can perform.
1192 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1193 return ICS;
1194 }
1195
1196 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001197 OverloadCandidateSet Conversions(From->getExprLoc(),
1198 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001199 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1200 Conversions, AllowExplicit,
1201 AllowObjCConversionOnExplicit)) {
1202 case OR_Success:
1203 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001204 ICS.setUserDefined();
1205 // C++ [over.ics.user]p4:
1206 // A conversion of an expression of class type to the same class
1207 // type is given Exact Match rank, and a conversion of an
1208 // expression of class type to a base class of that type is
1209 // given Conversion rank, in spite of the fact that a copy
1210 // constructor (i.e., a user-defined conversion function) is
1211 // called for those cases.
1212 if (CXXConstructorDecl *Constructor
1213 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1214 QualType FromCanon
1215 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1216 QualType ToCanon
1217 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1218 if (Constructor->isCopyConstructor() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00001219 (FromCanon == ToCanon ||
1220 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001221 // Turn this into a "standard" conversion sequence, so that it
1222 // gets ranked with standard conversion sequences.
Richard Smithc2bebe92016-05-11 20:37:46 +00001223 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001224 ICS.setStandard();
1225 ICS.Standard.setAsIdentityConversion();
1226 ICS.Standard.setFromType(From->getType());
1227 ICS.Standard.setAllToTypes(ToType);
1228 ICS.Standard.CopyConstructor = Constructor;
Richard Smithc2bebe92016-05-11 20:37:46 +00001229 ICS.Standard.FoundCopyConstructor = Found;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001230 if (ToCanon != FromCanon)
1231 ICS.Standard.Second = ICK_Derived_To_Base;
1232 }
1233 }
Richard Smith48372b62015-01-27 03:30:40 +00001234 break;
1235
1236 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001237 ICS.setAmbiguous();
1238 ICS.Ambiguous.setFromType(From->getType());
1239 ICS.Ambiguous.setToType(ToType);
1240 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1241 Cand != Conversions.end(); ++Cand)
1242 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00001243 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Richard Smith1bbaba82015-01-27 23:23:39 +00001244 break;
Richard Smith48372b62015-01-27 03:30:40 +00001245
1246 // Fall through.
1247 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001248 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001249 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001250 }
1251
1252 return ICS;
1253}
1254
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001255/// TryImplicitConversion - Attempt to perform an implicit conversion
1256/// from the given expression (Expr) to the given type (ToType). This
1257/// function returns an implicit conversion sequence that can be used
1258/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001259///
1260/// void f(float f);
1261/// void g(int i) { f(i); }
1262///
1263/// this routine would produce an implicit conversion sequence to
1264/// describe the initialization of f from i, which will be a standard
1265/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1266/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1267//
1268/// Note that this routine only determines how the conversion can be
1269/// performed; it does not actually perform the conversion. As such,
1270/// it will not produce any diagnostics if no conversion is available,
1271/// but will instead return an implicit conversion sequence of kind
1272/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001273///
1274/// If @p SuppressUserConversions, then user-defined conversions are
1275/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001276/// If @p AllowExplicit, then explicit user-defined conversions are
1277/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001278///
1279/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1280/// writeback conversion, which allows __autoreleasing id* parameters to
1281/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001282static ImplicitConversionSequence
1283TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1284 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001285 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001286 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001287 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001288 bool AllowObjCWritebackConversion,
1289 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001290 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001291 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001292 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001293 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001294 return ICS;
1295 }
1296
David Blaikiebbafb8a2012-03-11 07:00:24 +00001297 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001298 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001299 return ICS;
1300 }
1301
Douglas Gregor836a7e82010-08-11 02:15:33 +00001302 // C++ [over.ics.user]p4:
1303 // A conversion of an expression of class type to the same class
1304 // type is given Exact Match rank, and a conversion of an
1305 // expression of class type to a base class of that type is
1306 // given Conversion rank, in spite of the fact that a copy/move
1307 // constructor (i.e., a user-defined conversion function) is
1308 // called for those cases.
1309 QualType FromType = From->getType();
1310 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001311 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00001312 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001313 ICS.setStandard();
1314 ICS.Standard.setAsIdentityConversion();
1315 ICS.Standard.setFromType(FromType);
1316 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001317
Douglas Gregor5ab11652010-04-17 22:01:05 +00001318 // We don't actually check at this point whether there is a valid
1319 // copy/move constructor, since overloading just assumes that it
1320 // exists. When we actually perform initialization, we'll find the
1321 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001322 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001323
Douglas Gregor5ab11652010-04-17 22:01:05 +00001324 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001325 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001326 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001327
Douglas Gregor836a7e82010-08-11 02:15:33 +00001328 return ICS;
1329 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001330
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001331 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1332 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001333 AllowObjCWritebackConversion,
1334 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001335}
1336
John McCall31168b02011-06-15 23:02:42 +00001337ImplicitConversionSequence
1338Sema::TryImplicitConversion(Expr *From, QualType ToType,
1339 bool SuppressUserConversions,
1340 bool AllowExplicit,
1341 bool InOverloadResolution,
1342 bool CStyle,
1343 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001344 return ::TryImplicitConversion(*this, From, ToType,
1345 SuppressUserConversions, AllowExplicit,
1346 InOverloadResolution, CStyle,
1347 AllowObjCWritebackConversion,
1348 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001349}
1350
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001351/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001352/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001353/// converted expression. Flavor is the kind of conversion we're
1354/// performing, used in the error message. If @p AllowExplicit,
1355/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001356ExprResult
1357Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001358 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001359 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001360 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001361}
1362
John Wiegley01296292011-04-08 18:41:53 +00001363ExprResult
1364Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001365 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001366 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001367 if (checkPlaceholderForOverload(*this, From))
1368 return ExprError();
1369
John McCall31168b02011-06-15 23:02:42 +00001370 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1371 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001372 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001373 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001374 if (getLangOpts().ObjC1)
1375 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1376 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001377 ICS = ::TryImplicitConversion(*this, From, ToType,
1378 /*SuppressUserConversions=*/false,
1379 AllowExplicit,
1380 /*InOverloadResolution=*/false,
1381 /*CStyle=*/false,
1382 AllowObjCWritebackConversion,
1383 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001384 return PerformImplicitConversion(From, ToType, ICS, Action);
1385}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001386
1387/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001388/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001389bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1390 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001391 if (Context.hasSameUnqualifiedType(FromType, ToType))
1392 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001393
John McCall991eb4b2010-12-21 00:44:39 +00001394 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1395 // where F adds one of the following at most once:
1396 // - a pointer
1397 // - a member pointer
1398 // - a block pointer
1399 CanQualType CanTo = Context.getCanonicalType(ToType);
1400 CanQualType CanFrom = Context.getCanonicalType(FromType);
1401 Type::TypeClass TyClass = CanTo->getTypeClass();
1402 if (TyClass != CanFrom->getTypeClass()) return false;
1403 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1404 if (TyClass == Type::Pointer) {
1405 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1406 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1407 } else if (TyClass == Type::BlockPointer) {
1408 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1409 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1410 } else if (TyClass == Type::MemberPointer) {
1411 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1412 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1413 } else {
1414 return false;
1415 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001416
John McCall991eb4b2010-12-21 00:44:39 +00001417 TyClass = CanTo->getTypeClass();
1418 if (TyClass != CanFrom->getTypeClass()) return false;
1419 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1420 return false;
1421 }
1422
1423 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1424 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1425 if (!EInfo.getNoReturn()) return false;
1426
1427 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1428 assert(QualType(FromFn, 0).isCanonical());
1429 if (QualType(FromFn, 0) != CanTo) return false;
1430
1431 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001432 return true;
1433}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001434
Douglas Gregor46188682010-05-18 22:42:18 +00001435/// \brief Determine whether the conversion from FromType to ToType is a valid
1436/// vector conversion.
1437///
1438/// \param ICK Will be set to the vector conversion kind, if this is a vector
1439/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001440static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001441 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001442 // We need at least one of these types to be a vector type to have a vector
1443 // conversion.
1444 if (!ToType->isVectorType() && !FromType->isVectorType())
1445 return false;
1446
1447 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001448 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001449 return false;
1450
1451 // There are no conversions between extended vector types, only identity.
1452 if (ToType->isExtVectorType()) {
1453 // There are no conversions between extended vector types other than the
1454 // identity conversion.
1455 if (FromType->isExtVectorType())
1456 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001457
Douglas Gregor46188682010-05-18 22:42:18 +00001458 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001459 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001460 ICK = ICK_Vector_Splat;
1461 return true;
1462 }
1463 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001464
1465 // We can perform the conversion between vector types in the following cases:
1466 // 1)vector types are equivalent AltiVec and GCC vector types
1467 // 2)lax vector conversions are permitted and the vector types are of the
1468 // same size
1469 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001470 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1471 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001472 ICK = ICK_Vector_Conversion;
1473 return true;
1474 }
Douglas Gregor46188682010-05-18 22:42:18 +00001475 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001476
Douglas Gregor46188682010-05-18 22:42:18 +00001477 return false;
1478}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001479
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001480static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1481 bool InOverloadResolution,
1482 StandardConversionSequence &SCS,
1483 bool CStyle);
George Burgess IV45461812015-10-11 20:13:20 +00001484
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001485/// IsStandardConversion - Determines whether there is a standard
1486/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1487/// expression From to the type ToType. Standard conversion sequences
1488/// only consider non-class types; for conversions that involve class
1489/// types, use TryImplicitConversion. If a conversion exists, SCS will
1490/// contain the standard conversion sequence required to perform this
1491/// conversion and this routine will return true. Otherwise, this
1492/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001493static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1494 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001495 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001496 bool CStyle,
1497 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001498 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001499
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001500 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001501 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001502 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001503 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001504 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001505
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001506 // There are no standard conversions for class types in C++, so
George Burgess IV45461812015-10-11 20:13:20 +00001507 // abort early. When overloading in C, however, we do permit them.
1508 if (S.getLangOpts().CPlusPlus &&
1509 (FromType->isRecordType() || ToType->isRecordType()))
1510 return false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001511
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001512 // The first conversion can be an lvalue-to-rvalue conversion,
1513 // array-to-pointer conversion, or function-to-pointer conversion
1514 // (C++ 4p1).
1515
John McCall5c32be02010-08-24 20:38:10 +00001516 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001517 DeclAccessPair AccessPair;
1518 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001519 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001520 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001521 // We were able to resolve the address of the overloaded function,
1522 // so we can convert to the type of that function.
1523 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001524 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001525
1526 // we can sometimes resolve &foo<int> regardless of ToType, so check
1527 // if the type matches (identity) or we are converting to bool
1528 if (!S.Context.hasSameUnqualifiedType(
1529 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1530 QualType resultTy;
1531 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001532 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001533 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1534 // otherwise, only a boolean conversion is standard
1535 if (!ToType->isBooleanType())
1536 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001537 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001538
Chandler Carruthffce2452011-03-29 08:08:18 +00001539 // Check if the "from" expression is taking the address of an overloaded
1540 // function and recompute the FromType accordingly. Take advantage of the
1541 // fact that non-static member functions *must* have such an address-of
1542 // expression.
1543 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1544 if (Method && !Method->isStatic()) {
1545 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1546 "Non-unary operator on non-static member address");
1547 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1548 == UO_AddrOf &&
1549 "Non-address-of operator on non-static member address");
1550 const Type *ClassType
1551 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1552 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001553 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1554 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1555 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001556 "Non-address-of operator for overloaded function expression");
1557 FromType = S.Context.getPointerType(FromType);
1558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001559
Douglas Gregor980fb162010-04-29 18:24:40 +00001560 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001561 assert(S.Context.hasSameType(
1562 FromType,
1563 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001564 } else {
1565 return false;
1566 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001567 }
John McCall154a2fd2011-08-30 00:57:29 +00001568 // Lvalue-to-rvalue conversion (C++11 4.1):
1569 // A glvalue (3.10) of a non-function, non-array type T can
1570 // be converted to a prvalue.
1571 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001572 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001573 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001574 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001575 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576
Douglas Gregorc79862f2012-04-12 17:51:55 +00001577 // C11 6.3.2.1p2:
1578 // ... if the lvalue has atomic type, the value has the non-atomic version
1579 // of the type of the lvalue ...
1580 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1581 FromType = Atomic->getValueType();
1582
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001583 // If T is a non-class type, the type of the rvalue is the
1584 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001585 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1586 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001587 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001588 } else if (FromType->isArrayType()) {
1589 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001590 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001591
1592 // An lvalue or rvalue of type "array of N T" or "array of unknown
1593 // bound of T" can be converted to an rvalue of type "pointer to
1594 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001595 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001596
John McCall5c32be02010-08-24 20:38:10 +00001597 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001598 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001599 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001600
1601 // For the purpose of ranking in overload resolution
1602 // (13.3.3.1.1), this conversion is considered an
1603 // array-to-pointer conversion followed by a qualification
1604 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001605 SCS.Second = ICK_Identity;
1606 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001607 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001608 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001609 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001610 }
John McCall086a4642010-11-24 05:12:34 +00001611 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001612 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001613 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001614
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001615 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1616 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1617 if (!S.checkAddressOfFunctionIsAvailable(FD))
1618 return false;
1619
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001620 // An lvalue of function type T can be converted to an rvalue of
1621 // type "pointer to T." The result is a pointer to the
1622 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001623 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001624 } else {
1625 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001626 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001627 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001628 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001629
1630 // The second conversion can be an integral promotion, floating
1631 // point promotion, integral conversion, floating point conversion,
1632 // floating-integral conversion, pointer conversion,
1633 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001634 // For overloading in C, this can also be a "compatible-type"
1635 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001636 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001637 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001638 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001639 // The unqualified versions of the types are the same: there's no
1640 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001641 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001642 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001643 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001644 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001645 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001646 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001647 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001648 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001649 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001650 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001651 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001652 SCS.Second = ICK_Complex_Promotion;
1653 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001654 } else if (ToType->isBooleanType() &&
1655 (FromType->isArithmeticType() ||
1656 FromType->isAnyPointerType() ||
1657 FromType->isBlockPointerType() ||
1658 FromType->isMemberPointerType() ||
1659 FromType->isNullPtrType())) {
1660 // Boolean conversions (C++ 4.12).
1661 SCS.Second = ICK_Boolean_Conversion;
1662 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001663 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001664 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001665 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001666 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001667 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001668 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001669 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001670 SCS.Second = ICK_Complex_Conversion;
1671 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001672 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1673 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001674 // Complex-real conversions (C99 6.3.1.7)
1675 SCS.Second = ICK_Complex_Real;
1676 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001677 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001678 // FIXME: disable conversions between long double and __float128 if
1679 // their representation is different until there is back end support
1680 // We of course allow this conversion if long double is really double.
1681 if (&S.Context.getFloatTypeSemantics(FromType) !=
1682 &S.Context.getFloatTypeSemantics(ToType)) {
1683 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1684 ToType == S.Context.LongDoubleTy) ||
1685 (FromType == S.Context.LongDoubleTy &&
1686 ToType == S.Context.Float128Ty));
1687 if (Float128AndLongDouble &&
1688 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1689 &llvm::APFloat::IEEEdouble))
1690 return false;
1691 }
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001692 // Floating point conversions (C++ 4.8).
1693 SCS.Second = ICK_Floating_Conversion;
1694 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001695 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001696 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001697 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001698 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001699 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001700 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001701 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001702 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001703 SCS.Second = ICK_Block_Pointer_Conversion;
1704 } else if (AllowObjCWritebackConversion &&
1705 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1706 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001707 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1708 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001709 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001710 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001711 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001712 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001713 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001714 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001715 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001716 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001717 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001718 SCS.Second = SecondICK;
1719 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001720 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001721 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001722 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001723 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001724 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001725 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001726 // Treat a conversion that strips "noreturn" as an identity conversion.
1727 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001728 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1729 InOverloadResolution,
1730 SCS, CStyle)) {
1731 SCS.Second = ICK_TransparentUnionConversion;
1732 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001733 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1734 CStyle)) {
1735 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001736 // appropriately.
1737 return true;
George Burgess IV45461812015-10-11 20:13:20 +00001738 } else if (ToType->isEventT() &&
Guy Benyei259f9f42013-02-07 16:05:33 +00001739 From->isIntegerConstantExpr(S.getASTContext()) &&
George Burgess IV45461812015-10-11 20:13:20 +00001740 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
Guy Benyei259f9f42013-02-07 16:05:33 +00001741 SCS.Second = ICK_Zero_Event_Conversion;
1742 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001743 } else {
1744 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001745 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001746 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001747 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001749 QualType CanonFrom;
1750 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001751 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001752 bool ObjCLifetimeConversion;
1753 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1754 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001755 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001756 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001757 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001758 CanonFrom = S.Context.getCanonicalType(FromType);
1759 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001760 } else {
1761 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001762 SCS.Third = ICK_Identity;
1763
Mike Stump11289f42009-09-09 15:08:12 +00001764 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001765 // [...] Any difference in top-level cv-qualification is
1766 // subsumed by the initialization itself and does not constitute
1767 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001768 CanonFrom = S.Context.getCanonicalType(FromType);
1769 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001770 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001771 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001772 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001773 FromType = ToType;
1774 CanonFrom = CanonTo;
1775 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001776 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001777 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001778
George Burgess IV45461812015-10-11 20:13:20 +00001779 if (CanonFrom == CanonTo)
1780 return true;
1781
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001782 // If we have not converted the argument type to the parameter type,
George Burgess IV45461812015-10-11 20:13:20 +00001783 // this is a bad conversion sequence, unless we're resolving an overload in C.
1784 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001785 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001786
George Burgess IV45461812015-10-11 20:13:20 +00001787 ExprResult ER = ExprResult{From};
George Burgess IV2099b542016-09-02 22:59:57 +00001788 Sema::AssignConvertType Conv =
1789 S.CheckSingleAssignmentConstraints(ToType, ER,
1790 /*Diagnose=*/false,
1791 /*DiagnoseCFAudited=*/false,
1792 /*ConvertRHS=*/false);
George Burgess IV6098fd12016-09-03 00:28:25 +00001793 ImplicitConversionKind SecondConv;
George Burgess IV2099b542016-09-02 22:59:57 +00001794 switch (Conv) {
1795 case Sema::Compatible:
George Burgess IV6098fd12016-09-03 00:28:25 +00001796 SecondConv = ICK_C_Only_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001797 break;
1798 // For our purposes, discarding qualifiers is just as bad as using an
1799 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1800 // qualifiers, as well.
1801 case Sema::CompatiblePointerDiscardsQualifiers:
1802 case Sema::IncompatiblePointer:
1803 case Sema::IncompatiblePointerSign:
George Burgess IV6098fd12016-09-03 00:28:25 +00001804 SecondConv = ICK_Incompatible_Pointer_Conversion;
George Burgess IV2099b542016-09-02 22:59:57 +00001805 break;
1806 default:
George Burgess IV45461812015-10-11 20:13:20 +00001807 return false;
George Burgess IV2099b542016-09-02 22:59:57 +00001808 }
George Burgess IV45461812015-10-11 20:13:20 +00001809
George Burgess IV6098fd12016-09-03 00:28:25 +00001810 // First can only be an lvalue conversion, so we pretend that this was the
1811 // second conversion. First should already be valid from earlier in the
1812 // function.
1813 SCS.Second = SecondConv;
1814 SCS.setToType(1, ToType);
1815
1816 // Third is Identity, because Second should rank us worse than any other
1817 // conversion. This could also be ICK_Qualification, but it's simpler to just
1818 // lump everything in with the second conversion, and we don't gain anything
1819 // from making this ICK_Qualification.
1820 SCS.Third = ICK_Identity;
1821 SCS.setToType(2, ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001822 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001823}
George Burgess IV2099b542016-09-02 22:59:57 +00001824
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001825static bool
1826IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1827 QualType &ToType,
1828 bool InOverloadResolution,
1829 StandardConversionSequence &SCS,
1830 bool CStyle) {
1831
1832 const RecordType *UT = ToType->getAsUnionType();
1833 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1834 return false;
1835 // The field to initialize within the transparent union.
1836 RecordDecl *UD = UT->getDecl();
1837 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001838 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001839 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1840 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001841 ToType = it->getType();
1842 return true;
1843 }
1844 }
1845 return false;
1846}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001847
1848/// IsIntegralPromotion - Determines whether the conversion from the
1849/// expression From (whose potentially-adjusted type is FromType) to
1850/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1851/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001852bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001853 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001854 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001855 if (!To) {
1856 return false;
1857 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001858
1859 // An rvalue of type char, signed char, unsigned char, short int, or
1860 // unsigned short int can be converted to an rvalue of type int if
1861 // int can represent all the values of the source type; otherwise,
1862 // the source rvalue can be converted to an rvalue of type unsigned
1863 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001864 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1865 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001866 if (// We can promote any signed, promotable integer type to an int
1867 (FromType->isSignedIntegerType() ||
1868 // We can promote any unsigned integer type whose size is
1869 // less than int to an int.
Benjamin Kramer5ff67472016-04-11 08:26:13 +00001870 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001871 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001872 }
1873
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001874 return To->getKind() == BuiltinType::UInt;
1875 }
1876
Richard Smithb9c5a602012-09-13 21:18:54 +00001877 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001878 // A prvalue of an unscoped enumeration type whose underlying type is not
1879 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1880 // following types that can represent all the values of the enumeration
1881 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1882 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001883 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001884 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001885 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001886 // with lowest integer conversion rank (4.13) greater than the rank of long
1887 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001888 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001889 // C++11 [conv.prom]p4:
1890 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1891 // can be converted to a prvalue of its underlying type. Moreover, if
1892 // integral promotion can be applied to its underlying type, a prvalue of an
1893 // unscoped enumeration type whose underlying type is fixed can also be
1894 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001895 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1896 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1897 // provided for a scoped enumeration.
1898 if (FromEnumType->getDecl()->isScoped())
1899 return false;
1900
Richard Smithb9c5a602012-09-13 21:18:54 +00001901 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001902 // even if that's not the promoted type. Note that the check for promoting
1903 // the underlying type is based on the type alone, and does not consider
1904 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001905 if (FromEnumType->getDecl()->isFixed()) {
1906 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1907 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001908 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001909 }
1910
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001911 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001912 if (ToType->isIntegerType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001913 isCompleteType(From->getLocStart(), FromType))
Richard Smith88f4bba2015-03-26 00:16:07 +00001914 return Context.hasSameUnqualifiedType(
1915 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001916 }
John McCall56774992009-12-09 09:09:27 +00001917
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001918 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1920 // to an rvalue a prvalue of the first of the following types that can
1921 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001922 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001923 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001924 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001925 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001926 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001927 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001928 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001929 // Determine whether the type we're converting from is signed or
1930 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001931 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001932 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001933
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001934 // The types we'll try to promote to, in the appropriate
1935 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001936 QualType PromoteTypes[6] = {
1937 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001938 Context.LongTy, Context.UnsignedLongTy ,
1939 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001940 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001941 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001942 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1943 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001944 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001945 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1946 // We found the type that we can promote to. If this is the
1947 // type we wanted, we have a promotion. Otherwise, no
1948 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001949 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001950 }
1951 }
1952 }
1953
1954 // An rvalue for an integral bit-field (9.6) can be converted to an
1955 // rvalue of type int if int can represent all the values of the
1956 // bit-field; otherwise, it can be converted to unsigned int if
1957 // unsigned int can represent all the values of the bit-field. If
1958 // the bit-field is larger yet, no integral promotion applies to
1959 // it. If the bit-field has an enumerated type, it is treated as any
1960 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001961 // FIXME: We should delay checking of bit-fields until we actually perform the
1962 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001963 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001964 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001965 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001966 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001967 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001968 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001969 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001970
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001971 // Are we promoting to an int from a bitfield that fits in an int?
1972 if (BitWidth < ToSize ||
1973 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1974 return To->getKind() == BuiltinType::Int;
1975 }
Mike Stump11289f42009-09-09 15:08:12 +00001976
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001977 // Are we promoting to an unsigned int from an unsigned bitfield
1978 // that fits into an unsigned int?
1979 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1980 return To->getKind() == BuiltinType::UInt;
1981 }
Mike Stump11289f42009-09-09 15:08:12 +00001982
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001983 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001984 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001985 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001986 }
Mike Stump11289f42009-09-09 15:08:12 +00001987
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001988 // An rvalue of type bool can be converted to an rvalue of type int,
1989 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001990 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001991 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001992 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001993
1994 return false;
1995}
1996
1997/// IsFloatingPointPromotion - Determines whether the conversion from
1998/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1999/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00002000bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002001 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2002 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002003 /// An rvalue of type float can be converted to an rvalue of type
2004 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002005 if (FromBuiltin->getKind() == BuiltinType::Float &&
2006 ToBuiltin->getKind() == BuiltinType::Double)
2007 return true;
2008
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002009 // C99 6.3.1.5p1:
2010 // When a float is promoted to double or long double, or a
2011 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00002012 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002013 (FromBuiltin->getKind() == BuiltinType::Float ||
2014 FromBuiltin->getKind() == BuiltinType::Double) &&
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002015 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2016 ToBuiltin->getKind() == BuiltinType::Float128))
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002017 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002018
2019 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00002020 if (!getLangOpts().NativeHalfType &&
2021 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002022 ToBuiltin->getKind() == BuiltinType::Float)
2023 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002024 }
2025
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002026 return false;
2027}
2028
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002029/// \brief Determine if a conversion is a complex promotion.
2030///
2031/// A complex promotion is defined as a complex -> complex conversion
2032/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00002033/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002034bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00002035 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002036 if (!FromComplex)
2037 return false;
2038
John McCall9dd450b2009-09-21 23:43:11 +00002039 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002040 if (!ToComplex)
2041 return false;
2042
2043 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002044 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00002045 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00002046 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00002047}
2048
Douglas Gregor237f96c2008-11-26 23:31:11 +00002049/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2050/// the pointer type FromPtr to a pointer to type ToPointee, with the
2051/// same type qualifiers as FromPtr has on its pointee type. ToType,
2052/// if non-empty, will be a pointer to ToType that may or may not have
2053/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00002054///
Mike Stump11289f42009-09-09 15:08:12 +00002055static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002056BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002057 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002058 ASTContext &Context,
2059 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002060 assert((FromPtr->getTypeClass() == Type::Pointer ||
2061 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2062 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002063
John McCall31168b02011-06-15 23:02:42 +00002064 /// Conversions to 'id' subsume cv-qualifier conversions.
2065 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00002066 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002067
2068 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002069 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00002070 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00002071 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002072
John McCall31168b02011-06-15 23:02:42 +00002073 if (StripObjCLifetime)
2074 Quals.removeObjCLifetime();
2075
Mike Stump11289f42009-09-09 15:08:12 +00002076 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002077 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00002078 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00002079 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00002080 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002081
2082 // Build a pointer to ToPointee. It has the right qualifiers
2083 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002084 if (isa<ObjCObjectPointerType>(ToType))
2085 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00002086 return Context.getPointerType(ToPointee);
2087 }
2088
2089 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002090 QualType QualifiedCanonToPointee
2091 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002092
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002093 if (isa<ObjCObjectPointerType>(ToType))
2094 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2095 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002096}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002097
Mike Stump11289f42009-09-09 15:08:12 +00002098static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00002099 bool InOverloadResolution,
2100 ASTContext &Context) {
2101 // Handle value-dependent integral null pointer constants correctly.
2102 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2103 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002104 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00002105 return !InOverloadResolution;
2106
Douglas Gregor56751b52009-09-25 04:25:58 +00002107 return Expr->isNullPointerConstant(Context,
2108 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2109 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002110}
Mike Stump11289f42009-09-09 15:08:12 +00002111
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002112/// IsPointerConversion - Determines whether the conversion of the
2113/// expression From, which has the (possibly adjusted) type FromType,
2114/// can be converted to the type ToType via a pointer conversion (C++
2115/// 4.10). If so, returns true and places the converted type (that
2116/// might differ from ToType in its cv-qualifiers at some level) into
2117/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002118///
Douglas Gregora29dc052008-11-27 01:19:21 +00002119/// This routine also supports conversions to and from block pointers
2120/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2121/// pointers to interfaces. FIXME: Once we've determined the
2122/// appropriate overloading rules for Objective-C, we may want to
2123/// split the Objective-C checks into a different routine; however,
2124/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002125/// conversions, so for now they live here. IncompatibleObjC will be
2126/// set if the conversion is an allowed Objective-C conversion that
2127/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002128bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002129 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002130 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002131 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002132 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002133 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2134 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002135 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002136
Mike Stump11289f42009-09-09 15:08:12 +00002137 // Conversion from a null pointer constant to any Objective-C pointer type.
2138 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002139 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002140 ConvertedType = ToType;
2141 return true;
2142 }
2143
Douglas Gregor231d1c62008-11-27 00:15:41 +00002144 // Blocks: Block pointers can be converted to void*.
2145 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002146 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002147 ConvertedType = ToType;
2148 return true;
2149 }
2150 // Blocks: A null pointer constant can be converted to a block
2151 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002152 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002153 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002154 ConvertedType = ToType;
2155 return true;
2156 }
2157
Sebastian Redl576fd422009-05-10 18:38:11 +00002158 // If the left-hand-side is nullptr_t, the right side can be a null
2159 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002160 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002161 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002162 ConvertedType = ToType;
2163 return true;
2164 }
2165
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002166 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002167 if (!ToTypePtr)
2168 return false;
2169
2170 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002171 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002172 ConvertedType = ToType;
2173 return true;
2174 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002175
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002177 // , including objective-c pointers.
2178 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002179 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002180 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002181 ConvertedType = BuildSimilarlyQualifiedPointerType(
2182 FromType->getAs<ObjCObjectPointerType>(),
2183 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002184 ToType, Context);
2185 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002186 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002187 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002188 if (!FromTypePtr)
2189 return false;
2190
2191 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002192
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002193 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002194 // pointer conversion, so don't do all of the work below.
2195 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2196 return false;
2197
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002198 // An rvalue of type "pointer to cv T," where T is an object type,
2199 // can be converted to an rvalue of type "pointer to cv void" (C++
2200 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002201 if (FromPointeeType->isIncompleteOrObjectType() &&
2202 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002203 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002204 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002205 ToType, Context,
2206 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002207 return true;
2208 }
2209
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002210 // MSVC allows implicit function to void* type conversion.
David Majnemer6bf02822015-10-31 08:42:14 +00002211 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002212 ToPointeeType->isVoidType()) {
2213 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2214 ToPointeeType,
2215 ToType, Context);
2216 return true;
2217 }
2218
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002219 // When we're overloading in C, we allow a special kind of pointer
2220 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002221 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002222 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002223 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002224 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002225 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002226 return true;
2227 }
2228
Douglas Gregor5c407d92008-10-23 00:40:37 +00002229 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002230 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002231 // An rvalue of type "pointer to cv D," where D is a class type,
2232 // can be converted to an rvalue of type "pointer to cv B," where
2233 // B is a base class (clause 10) of D. If B is an inaccessible
2234 // (clause 11) or ambiguous (10.2) base class of D, a program that
2235 // necessitates this conversion is ill-formed. The result of the
2236 // conversion is a pointer to the base class sub-object of the
2237 // derived class object. The null pointer value is converted to
2238 // the null pointer value of the destination type.
2239 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002240 // Note that we do not check for ambiguity or inaccessibility
2241 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002242 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002243 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002244 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002245 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002246 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002247 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002248 ToType, Context);
2249 return true;
2250 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002251
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002252 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2253 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2254 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2255 ToPointeeType,
2256 ToType, Context);
2257 return true;
2258 }
2259
Douglas Gregora119f102008-12-19 19:13:09 +00002260 return false;
2261}
Douglas Gregoraec25842011-04-26 23:16:46 +00002262
2263/// \brief Adopt the given qualifiers for the given type.
2264static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2265 Qualifiers TQs = T.getQualifiers();
2266
2267 // Check whether qualifiers already match.
2268 if (TQs == Qs)
2269 return T;
2270
2271 if (Qs.compatiblyIncludes(TQs))
2272 return Context.getQualifiedType(T, Qs);
2273
2274 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2275}
Douglas Gregora119f102008-12-19 19:13:09 +00002276
2277/// isObjCPointerConversion - Determines whether this is an
2278/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2279/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002280bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002281 QualType& ConvertedType,
2282 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002283 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002284 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002285
Douglas Gregoraec25842011-04-26 23:16:46 +00002286 // The set of qualifiers on the type we're converting from.
2287 Qualifiers FromQualifiers = FromType.getQualifiers();
2288
Steve Naroff7cae42b2009-07-10 23:34:53 +00002289 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002290 const ObjCObjectPointerType* ToObjCPtr =
2291 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002292 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002293 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002294
Steve Naroff7cae42b2009-07-10 23:34:53 +00002295 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002296 // If the pointee types are the same (ignoring qualifications),
2297 // then this is not a pointer conversion.
2298 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2299 FromObjCPtr->getPointeeType()))
2300 return false;
2301
Douglas Gregorab209d82015-07-07 03:58:42 +00002302 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002303 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002304 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2305 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002306 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002307 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2308 FromObjCPtr->getPointeeType()))
2309 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002310 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002311 ToObjCPtr->getPointeeType(),
2312 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002313 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002314 return true;
2315 }
2316
2317 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2318 // Okay: this is some kind of implicit downcast of Objective-C
2319 // interfaces, which is permitted. However, we're going to
2320 // complain about it.
2321 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002322 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002323 ToObjCPtr->getPointeeType(),
2324 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002325 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002326 return true;
2327 }
Mike Stump11289f42009-09-09 15:08:12 +00002328 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002329 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002330 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002331 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002332 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002333 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002334 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002335 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002336 // to a block pointer type.
2337 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002338 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002339 return true;
2340 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002341 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002342 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002343 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002344 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002345 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002346 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002347 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002348 return true;
2349 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002350 else
Douglas Gregora119f102008-12-19 19:13:09 +00002351 return false;
2352
Douglas Gregor033f56d2008-12-23 00:53:59 +00002353 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002354 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002355 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002356 else if (const BlockPointerType *FromBlockPtr =
2357 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002358 FromPointeeType = FromBlockPtr->getPointeeType();
2359 else
Douglas Gregora119f102008-12-19 19:13:09 +00002360 return false;
2361
Douglas Gregora119f102008-12-19 19:13:09 +00002362 // If we have pointers to pointers, recursively check whether this
2363 // is an Objective-C conversion.
2364 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2365 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2366 IncompatibleObjC)) {
2367 // We always complain about this conversion.
2368 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002369 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002370 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002371 return true;
2372 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002373 // Allow conversion of pointee being objective-c pointer to another one;
2374 // as in I* to id.
2375 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2376 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2377 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2378 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002379
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002380 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002381 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002382 return true;
2383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002384
Douglas Gregor033f56d2008-12-23 00:53:59 +00002385 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002386 // differences in the argument and result types are in Objective-C
2387 // pointer conversions. If so, we permit the conversion (but
2388 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002389 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002390 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002391 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002392 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002393 if (FromFunctionType && ToFunctionType) {
2394 // If the function types are exactly the same, this isn't an
2395 // Objective-C pointer conversion.
2396 if (Context.getCanonicalType(FromPointeeType)
2397 == Context.getCanonicalType(ToPointeeType))
2398 return false;
2399
2400 // Perform the quick checks that will tell us whether these
2401 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002402 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002403 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2404 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2405 return false;
2406
2407 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002408 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2409 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002410 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002411 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2412 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002413 ConvertedType, IncompatibleObjC)) {
2414 // Okay, we have an Objective-C pointer conversion.
2415 HasObjCConversion = true;
2416 } else {
2417 // Function types are too different. Abort.
2418 return false;
2419 }
Mike Stump11289f42009-09-09 15:08:12 +00002420
Douglas Gregora119f102008-12-19 19:13:09 +00002421 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002422 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002423 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002424 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2425 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002426 if (Context.getCanonicalType(FromArgType)
2427 == Context.getCanonicalType(ToArgType)) {
2428 // Okay, the types match exactly. Nothing to do.
2429 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2430 ConvertedType, IncompatibleObjC)) {
2431 // Okay, we have an Objective-C pointer conversion.
2432 HasObjCConversion = true;
2433 } else {
2434 // Argument types are too different. Abort.
2435 return false;
2436 }
2437 }
2438
2439 if (HasObjCConversion) {
2440 // We had an Objective-C conversion. Allow this pointer
2441 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002442 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002443 IncompatibleObjC = true;
2444 return true;
2445 }
2446 }
2447
Sebastian Redl72b597d2009-01-25 19:43:20 +00002448 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002449}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002450
John McCall31168b02011-06-15 23:02:42 +00002451/// \brief Determine whether this is an Objective-C writeback conversion,
2452/// used for parameter passing when performing automatic reference counting.
2453///
2454/// \param FromType The type we're converting form.
2455///
2456/// \param ToType The type we're converting to.
2457///
2458/// \param ConvertedType The type that will be produced after applying
2459/// this conversion.
2460bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2461 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002462 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002463 Context.hasSameUnqualifiedType(FromType, ToType))
2464 return false;
2465
2466 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2467 QualType ToPointee;
2468 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2469 ToPointee = ToPointer->getPointeeType();
2470 else
2471 return false;
2472
2473 Qualifiers ToQuals = ToPointee.getQualifiers();
2474 if (!ToPointee->isObjCLifetimeType() ||
2475 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002476 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002477 return false;
2478
2479 // Argument must be a pointer to __strong to __weak.
2480 QualType FromPointee;
2481 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2482 FromPointee = FromPointer->getPointeeType();
2483 else
2484 return false;
2485
2486 Qualifiers FromQuals = FromPointee.getQualifiers();
2487 if (!FromPointee->isObjCLifetimeType() ||
2488 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2489 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2490 return false;
2491
2492 // Make sure that we have compatible qualifiers.
2493 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2494 if (!ToQuals.compatiblyIncludes(FromQuals))
2495 return false;
2496
2497 // Remove qualifiers from the pointee type we're converting from; they
2498 // aren't used in the compatibility check belong, and we'll be adding back
2499 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2500 FromPointee = FromPointee.getUnqualifiedType();
2501
2502 // The unqualified form of the pointee types must be compatible.
2503 ToPointee = ToPointee.getUnqualifiedType();
2504 bool IncompatibleObjC;
2505 if (Context.typesAreCompatible(FromPointee, ToPointee))
2506 FromPointee = ToPointee;
2507 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2508 IncompatibleObjC))
2509 return false;
2510
2511 /// \brief Construct the type we're converting to, which is a pointer to
2512 /// __autoreleasing pointee.
2513 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2514 ConvertedType = Context.getPointerType(FromPointee);
2515 return true;
2516}
2517
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002518bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2519 QualType& ConvertedType) {
2520 QualType ToPointeeType;
2521 if (const BlockPointerType *ToBlockPtr =
2522 ToType->getAs<BlockPointerType>())
2523 ToPointeeType = ToBlockPtr->getPointeeType();
2524 else
2525 return false;
2526
2527 QualType FromPointeeType;
2528 if (const BlockPointerType *FromBlockPtr =
2529 FromType->getAs<BlockPointerType>())
2530 FromPointeeType = FromBlockPtr->getPointeeType();
2531 else
2532 return false;
2533 // We have pointer to blocks, check whether the only
2534 // differences in the argument and result types are in Objective-C
2535 // pointer conversions. If so, we permit the conversion.
2536
2537 const FunctionProtoType *FromFunctionType
2538 = FromPointeeType->getAs<FunctionProtoType>();
2539 const FunctionProtoType *ToFunctionType
2540 = ToPointeeType->getAs<FunctionProtoType>();
2541
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002542 if (!FromFunctionType || !ToFunctionType)
2543 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002544
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002545 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002546 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002547
2548 // Perform the quick checks that will tell us whether these
2549 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002550 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002551 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2552 return false;
2553
2554 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2555 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2556 if (FromEInfo != ToEInfo)
2557 return false;
2558
2559 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002560 if (Context.hasSameType(FromFunctionType->getReturnType(),
2561 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002562 // Okay, the types match exactly. Nothing to do.
2563 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002564 QualType RHS = FromFunctionType->getReturnType();
2565 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002566 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002567 !RHS.hasQualifiers() && LHS.hasQualifiers())
2568 LHS = LHS.getUnqualifiedType();
2569
2570 if (Context.hasSameType(RHS,LHS)) {
2571 // OK exact match.
2572 } else if (isObjCPointerConversion(RHS, LHS,
2573 ConvertedType, IncompatibleObjC)) {
2574 if (IncompatibleObjC)
2575 return false;
2576 // Okay, we have an Objective-C pointer conversion.
2577 }
2578 else
2579 return false;
2580 }
2581
2582 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002583 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002584 ArgIdx != NumArgs; ++ArgIdx) {
2585 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002586 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2587 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002588 if (Context.hasSameType(FromArgType, ToArgType)) {
2589 // Okay, the types match exactly. Nothing to do.
2590 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2591 ConvertedType, IncompatibleObjC)) {
2592 if (IncompatibleObjC)
2593 return false;
2594 // Okay, we have an Objective-C pointer conversion.
2595 } else
2596 // Argument types are too different. Abort.
2597 return false;
2598 }
John McCall18afab72016-03-01 00:49:02 +00002599 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2600 ToFunctionType))
Fariborz Jahanian97676972011-09-28 21:52:05 +00002601 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002602
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002603 ConvertedType = ToType;
2604 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002605}
2606
Richard Trieucaff2472011-11-23 22:32:32 +00002607enum {
2608 ft_default,
2609 ft_different_class,
2610 ft_parameter_arity,
2611 ft_parameter_mismatch,
2612 ft_return_type,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002613 ft_qualifer_mismatch
Richard Trieucaff2472011-11-23 22:32:32 +00002614};
2615
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002616/// Attempts to get the FunctionProtoType from a Type. Handles
2617/// MemberFunctionPointers properly.
2618static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2619 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2620 return FPT;
2621
2622 if (auto *MPT = FromType->getAs<MemberPointerType>())
2623 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2624
2625 return nullptr;
2626}
2627
Richard Trieucaff2472011-11-23 22:32:32 +00002628/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2629/// function types. Catches different number of parameter, mismatch in
2630/// parameter types, and different return types.
2631void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2632 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002633 // If either type is not valid, include no extra info.
2634 if (FromType.isNull() || ToType.isNull()) {
2635 PDiag << ft_default;
2636 return;
2637 }
2638
Richard Trieucaff2472011-11-23 22:32:32 +00002639 // Get the function type from the pointers.
2640 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2641 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2642 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002643 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002644 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2645 << QualType(FromMember->getClass(), 0);
2646 return;
2647 }
2648 FromType = FromMember->getPointeeType();
2649 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002650 }
2651
Richard Trieu96ed5b62011-12-13 23:19:45 +00002652 if (FromType->isPointerType())
2653 FromType = FromType->getPointeeType();
2654 if (ToType->isPointerType())
2655 ToType = ToType->getPointeeType();
2656
2657 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002658 FromType = FromType.getNonReferenceType();
2659 ToType = ToType.getNonReferenceType();
2660
Richard Trieucaff2472011-11-23 22:32:32 +00002661 // Don't print extra info for non-specialized template functions.
2662 if (FromType->isInstantiationDependentType() &&
2663 !FromType->getAs<TemplateSpecializationType>()) {
2664 PDiag << ft_default;
2665 return;
2666 }
2667
Richard Trieu96ed5b62011-12-13 23:19:45 +00002668 // No extra info for same types.
2669 if (Context.hasSameType(FromType, ToType)) {
2670 PDiag << ft_default;
2671 return;
2672 }
2673
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002674 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2675 *ToFunction = tryGetFunctionProtoType(ToType);
Richard Trieucaff2472011-11-23 22:32:32 +00002676
2677 // Both types need to be function types.
2678 if (!FromFunction || !ToFunction) {
2679 PDiag << ft_default;
2680 return;
2681 }
2682
Alp Toker9cacbab2014-01-20 20:26:09 +00002683 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2684 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2685 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002686 return;
2687 }
2688
2689 // Handle different parameter types.
2690 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002691 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002692 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002693 << ToFunction->getParamType(ArgPos)
2694 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002695 return;
2696 }
2697
2698 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002699 if (!Context.hasSameType(FromFunction->getReturnType(),
2700 ToFunction->getReturnType())) {
2701 PDiag << ft_return_type << ToFunction->getReturnType()
2702 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002703 return;
2704 }
2705
2706 unsigned FromQuals = FromFunction->getTypeQuals(),
2707 ToQuals = ToFunction->getTypeQuals();
2708 if (FromQuals != ToQuals) {
2709 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2710 return;
2711 }
2712
2713 // Unable to find a difference, so add no extra info.
2714 PDiag << ft_default;
2715}
2716
Alp Toker9cacbab2014-01-20 20:26:09 +00002717/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002718/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002719/// they have same number of arguments. If the parameters are different,
2720/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002721bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2722 const FunctionProtoType *NewType,
2723 unsigned *ArgPos) {
2724 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2725 N = NewType->param_type_begin(),
2726 E = OldType->param_type_end();
2727 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002728 if (!Context.hasSameType(O->getUnqualifiedType(),
2729 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002730 if (ArgPos)
2731 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002732 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002733 }
2734 }
2735 return true;
2736}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002737
Douglas Gregor39c16d42008-10-24 04:54:22 +00002738/// CheckPointerConversion - Check the pointer conversion from the
2739/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002740/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002741/// conversions for which IsPointerConversion has already returned
2742/// true. It returns true and produces a diagnostic if there was an
2743/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002744bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002745 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002746 CXXCastPath& BasePath,
George Burgess IV60bc9722016-01-13 23:36:34 +00002747 bool IgnoreBaseAccess,
2748 bool Diagnose) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002749 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002750 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002751
John McCall8cb679e2010-11-15 09:13:47 +00002752 Kind = CK_BitCast;
2753
George Burgess IV60bc9722016-01-13 23:36:34 +00002754 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002755 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
George Burgess IV60bc9722016-01-13 23:36:34 +00002756 Expr::NPCK_ZeroExpression) {
David Blaikie1c7c8f72012-08-08 17:33:31 +00002757 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2758 DiagRuntimeBehavior(From->getExprLoc(), From,
2759 PDiag(diag::warn_impcast_bool_to_null_pointer)
2760 << ToType << From->getSourceRange());
2761 else if (!isUnevaluatedContext())
2762 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2763 << ToType << From->getSourceRange();
2764 }
John McCall9320b872011-09-09 05:25:32 +00002765 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2766 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002767 QualType FromPointeeType = FromPtrType->getPointeeType(),
2768 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002769
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002770 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2771 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002772 // We must have a derived-to-base conversion. Check an
2773 // ambiguous or inaccessible conversion.
George Burgess IV60bc9722016-01-13 23:36:34 +00002774 unsigned InaccessibleID = 0;
2775 unsigned AmbigiousID = 0;
2776 if (Diagnose) {
2777 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2778 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2779 }
2780 if (CheckDerivedToBaseConversion(
2781 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2782 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2783 &BasePath, IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002784 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002785
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002786 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002787 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002788 }
David Majnemer6bf02822015-10-31 08:42:14 +00002789
George Burgess IV60bc9722016-01-13 23:36:34 +00002790 if (Diagnose && !IsCStyleOrFunctionalCast &&
2791 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
David Majnemer6bf02822015-10-31 08:42:14 +00002792 assert(getLangOpts().MSVCCompat &&
2793 "this should only be possible with MSVCCompat!");
2794 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2795 << From->getSourceRange();
2796 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002797 }
John McCall9320b872011-09-09 05:25:32 +00002798 } else if (const ObjCObjectPointerType *ToPtrType =
2799 ToType->getAs<ObjCObjectPointerType>()) {
2800 if (const ObjCObjectPointerType *FromPtrType =
2801 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002802 // Objective-C++ conversions are always okay.
2803 // FIXME: We should have a different class of conversions for the
2804 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002805 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002806 return false;
John McCall9320b872011-09-09 05:25:32 +00002807 } else if (FromType->isBlockPointerType()) {
2808 Kind = CK_BlockPointerToObjCPointerCast;
2809 } else {
2810 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002811 }
John McCall9320b872011-09-09 05:25:32 +00002812 } else if (ToType->isBlockPointerType()) {
2813 if (!FromType->isBlockPointerType())
2814 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002815 }
John McCall8cb679e2010-11-15 09:13:47 +00002816
2817 // We shouldn't fall into this case unless it's valid for other
2818 // reasons.
2819 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2820 Kind = CK_NullToPointer;
2821
Douglas Gregor39c16d42008-10-24 04:54:22 +00002822 return false;
2823}
2824
Sebastian Redl72b597d2009-01-25 19:43:20 +00002825/// IsMemberPointerConversion - Determines whether the conversion of the
2826/// expression From, which has the (possibly adjusted) type FromType, can be
2827/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2828/// If so, returns true and places the converted type (that might differ from
2829/// ToType in its cv-qualifiers at some level) into ConvertedType.
2830bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002831 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002832 bool InOverloadResolution,
2833 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002834 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002835 if (!ToTypePtr)
2836 return false;
2837
2838 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002839 if (From->isNullPointerConstant(Context,
2840 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2841 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002842 ConvertedType = ToType;
2843 return true;
2844 }
2845
2846 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002847 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002848 if (!FromTypePtr)
2849 return false;
2850
2851 // A pointer to member of B can be converted to a pointer to member of D,
2852 // where D is derived from B (C++ 4.11p2).
2853 QualType FromClass(FromTypePtr->getClass(), 0);
2854 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002855
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002856 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002857 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002858 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2859 ToClass.getTypePtr());
2860 return true;
2861 }
2862
2863 return false;
2864}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002865
Sebastian Redl72b597d2009-01-25 19:43:20 +00002866/// CheckMemberPointerConversion - Check the member pointer conversion from the
2867/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002868/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002869/// for which IsMemberPointerConversion has already returned true. It returns
2870/// true and produces a diagnostic if there was an error, or returns false
2871/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002872bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002873 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002874 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002875 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002876 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002877 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002878 if (!FromPtrType) {
2879 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002880 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002881 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002882 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002883 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002884 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002885 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002886
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002887 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002888 assert(ToPtrType && "No member pointer cast has a target type "
2889 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002890
Sebastian Redled8f2002009-01-28 18:33:18 +00002891 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2892 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002893
Sebastian Redled8f2002009-01-28 18:33:18 +00002894 // FIXME: What about dependent types?
2895 assert(FromClass->isRecordType() && "Pointer into non-class.");
2896 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002897
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002898 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002899 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002900 bool DerivationOkay =
2901 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
Sebastian Redled8f2002009-01-28 18:33:18 +00002902 assert(DerivationOkay &&
2903 "Should not have been called if derivation isn't OK.");
2904 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002905
Sebastian Redled8f2002009-01-28 18:33:18 +00002906 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2907 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002908 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2909 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2910 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2911 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002912 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002913
Douglas Gregor89ee6822009-02-28 01:32:25 +00002914 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002915 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2916 << FromClass << ToClass << QualType(VBase, 0)
2917 << From->getSourceRange();
2918 return true;
2919 }
2920
John McCall5b0829a2010-02-10 09:31:12 +00002921 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002922 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2923 Paths.front(),
2924 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002925
Anders Carlssond7923c62009-08-22 23:33:40 +00002926 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002927 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002928 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002929 return false;
2930}
2931
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002932/// Determine whether the lifetime conversion between the two given
2933/// qualifiers sets is nontrivial.
2934static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2935 Qualifiers ToQuals) {
2936 // Converting anything to const __unsafe_unretained is trivial.
2937 if (ToQuals.hasConst() &&
2938 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2939 return false;
2940
2941 return true;
2942}
2943
Douglas Gregor9a657932008-10-21 23:43:52 +00002944/// IsQualificationConversion - Determines whether the conversion from
2945/// an rvalue of type FromType to ToType is a qualification conversion
2946/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002947///
2948/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2949/// when the qualification conversion involves a change in the Objective-C
2950/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002951bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002953 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002954 FromType = Context.getCanonicalType(FromType);
2955 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002956 ObjCLifetimeConversion = false;
2957
Douglas Gregor9a657932008-10-21 23:43:52 +00002958 // If FromType and ToType are the same type, this is not a
2959 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002960 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002961 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002962
Douglas Gregor9a657932008-10-21 23:43:52 +00002963 // (C++ 4.4p4):
2964 // A conversion can add cv-qualifiers at levels other than the first
2965 // in multi-level pointers, subject to the following rules: [...]
2966 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002967 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002968 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002969 // Within each iteration of the loop, we check the qualifiers to
2970 // determine if this still looks like a qualification
2971 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002972 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002973 // until there are no more pointers or pointers-to-members left to
2974 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002975 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002976
Douglas Gregor90609aa2011-04-25 18:40:17 +00002977 Qualifiers FromQuals = FromType.getQualifiers();
2978 Qualifiers ToQuals = ToType.getQualifiers();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00002979
2980 // Ignore __unaligned qualifier if this type is void.
2981 if (ToType.getUnqualifiedType()->isVoidType())
2982 FromQuals.removeUnaligned();
Douglas Gregor90609aa2011-04-25 18:40:17 +00002983
John McCall31168b02011-06-15 23:02:42 +00002984 // Objective-C ARC:
2985 // Check Objective-C lifetime conversions.
2986 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2987 UnwrappedAnyPointer) {
2988 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002989 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2990 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002991 FromQuals.removeObjCLifetime();
2992 ToQuals.removeObjCLifetime();
2993 } else {
2994 // Qualification conversions cannot cast between different
2995 // Objective-C lifetime qualifiers.
2996 return false;
2997 }
2998 }
2999
Douglas Gregorf30053d2011-05-08 06:09:53 +00003000 // Allow addition/removal of GC attributes but not changing GC attributes.
3001 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3002 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3003 FromQuals.removeObjCGCAttr();
3004 ToQuals.removeObjCGCAttr();
3005 }
3006
Douglas Gregor9a657932008-10-21 23:43:52 +00003007 // -- for every j > 0, if const is in cv 1,j then const is in cv
3008 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003009 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00003010 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003011
Douglas Gregor9a657932008-10-21 23:43:52 +00003012 // -- if the cv 1,j and cv 2,j are different, then const is in
3013 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00003014 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003015 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00003016 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003017
Douglas Gregor9a657932008-10-21 23:43:52 +00003018 // Keep track of whether all prior cv-qualifiers in the "to" type
3019 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00003020 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00003021 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003022 }
Douglas Gregor9a657932008-10-21 23:43:52 +00003023
3024 // We are left with FromType and ToType being the pointee types
3025 // after unwrapping the original FromType and ToType the same number
3026 // of types. If we unwrapped any pointers, and if FromType and
3027 // ToType have the same unqualified type (since we checked
3028 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003029 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00003030}
3031
Douglas Gregorc79862f2012-04-12 17:51:55 +00003032/// \brief - Determine whether this is a conversion from a scalar type to an
3033/// atomic type.
3034///
3035/// If successful, updates \c SCS's second and third steps in the conversion
3036/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00003037static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3038 bool InOverloadResolution,
3039 StandardConversionSequence &SCS,
3040 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00003041 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3042 if (!ToAtomic)
3043 return false;
3044
3045 StandardConversionSequence InnerSCS;
3046 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3047 InOverloadResolution, InnerSCS,
3048 CStyle, /*AllowObjCWritebackConversion=*/false))
3049 return false;
3050
3051 SCS.Second = InnerSCS.Second;
3052 SCS.setToType(1, InnerSCS.getToType(1));
3053 SCS.Third = InnerSCS.Third;
3054 SCS.QualificationIncludesObjCLifetime
3055 = InnerSCS.QualificationIncludesObjCLifetime;
3056 SCS.setToType(2, InnerSCS.getToType(2));
3057 return true;
3058}
3059
Sebastian Redle5417162012-03-27 18:33:03 +00003060static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3061 CXXConstructorDecl *Constructor,
3062 QualType Type) {
3063 const FunctionProtoType *CtorType =
3064 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003065 if (CtorType->getNumParams() > 0) {
3066 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00003067 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3068 return true;
3069 }
3070 return false;
3071}
3072
Sebastian Redl82ace982012-02-11 23:51:08 +00003073static OverloadingResult
3074IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3075 CXXRecordDecl *To,
3076 UserDefinedConversionSequence &User,
3077 OverloadCandidateSet &CandidateSet,
3078 bool AllowExplicit) {
Richard Smithc2bebe92016-05-11 20:37:46 +00003079 for (auto *D : S.LookupConstructors(To)) {
3080 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003081 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003082 continue;
Sebastian Redl82ace982012-02-11 23:51:08 +00003083
Richard Smithc2bebe92016-05-11 20:37:46 +00003084 bool Usable = !Info.Constructor->isInvalidDecl() &&
3085 S.isInitListConstructor(Info.Constructor) &&
3086 (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl82ace982012-02-11 23:51:08 +00003087 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00003088 // If the first argument is (a reference to) the target type,
3089 // suppress conversions.
Richard Smithc2bebe92016-05-11 20:37:46 +00003090 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3091 S.Context, Info.Constructor, ToType);
3092 if (Info.ConstructorTmpl)
3093 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3094 /*ExplicitArgs*/ nullptr, From,
3095 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003096 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003097 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3098 CandidateSet, SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00003099 }
3100 }
3101
3102 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3103
3104 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003105 switch (auto Result =
3106 CandidateSet.BestViableFunction(S, From->getLocStart(),
3107 Best, true)) {
3108 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00003109 case OR_Success: {
3110 // Record the standard conversion we used and the conversion function.
3111 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00003112 QualType ThisType = Constructor->getThisType(S.Context);
3113 // Initializer lists don't have conversions as such.
3114 User.Before.setAsIdentityConversion();
3115 User.HadMultipleCandidates = HadMultipleCandidates;
3116 User.ConversionFunction = Constructor;
3117 User.FoundConversionFunction = Best->FoundDecl;
3118 User.After.setAsIdentityConversion();
3119 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3120 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00003121 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00003122 }
3123
3124 case OR_No_Viable_Function:
3125 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00003126 case OR_Ambiguous:
3127 return OR_Ambiguous;
3128 }
3129
3130 llvm_unreachable("Invalid OverloadResult!");
3131}
3132
Douglas Gregor576e98c2009-01-30 23:27:23 +00003133/// Determines whether there is a user-defined conversion sequence
3134/// (C++ [over.ics.user]) that converts expression From to the type
3135/// ToType. If such a conversion exists, User will contain the
3136/// user-defined conversion sequence that performs such a conversion
3137/// and this routine will return true. Otherwise, this routine returns
3138/// false and User is unspecified.
3139///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003140/// \param AllowExplicit true if the conversion should consider C++0x
3141/// "explicit" conversion functions as well as non-explicit conversion
3142/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003143///
3144/// \param AllowObjCConversionOnExplicit true if the conversion should
3145/// allow an extra Objective-C pointer conversion on uses of explicit
3146/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003147static OverloadingResult
3148IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003149 UserDefinedConversionSequence &User,
3150 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003151 bool AllowExplicit,
3152 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003153 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003154
Douglas Gregor5ab11652010-04-17 22:01:05 +00003155 // Whether we will only visit constructors.
3156 bool ConstructorsOnly = false;
3157
3158 // If the type we are conversion to is a class type, enumerate its
3159 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003160 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003161 // C++ [over.match.ctor]p1:
3162 // When objects of class type are direct-initialized (8.5), or
3163 // copy-initialized from an expression of the same or a
3164 // derived class type (8.5), overload resolution selects the
3165 // constructor. [...] For copy-initialization, the candidate
3166 // functions are all the converting constructors (12.3.1) of
3167 // that class. The argument list is the expression-list within
3168 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003169 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003170 (From->getType()->getAs<RecordType>() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00003171 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003172 ConstructorsOnly = true;
3173
Richard Smithdb0ac552015-12-18 22:40:25 +00003174 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003175 // We're not going to find any constructors.
3176 } else if (CXXRecordDecl *ToRecordDecl
3177 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003178
3179 Expr **Args = &From;
3180 unsigned NumArgs = 1;
3181 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003182 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003183 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003184 OverloadingResult Result = IsInitializerListConstructorConversion(
3185 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3186 if (Result != OR_No_Viable_Function)
3187 return Result;
3188 // Never mind.
3189 CandidateSet.clear();
3190
3191 // If we're list-initializing, we pass the individual elements as
3192 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003193 Args = InitList->getInits();
3194 NumArgs = InitList->getNumInits();
3195 ListInitializing = true;
3196 }
3197
Richard Smithc2bebe92016-05-11 20:37:46 +00003198 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3199 auto Info = getConstructorInfo(D);
Richard Smith5179eb72016-06-28 19:03:57 +00003200 if (!Info)
Richard Smithc2bebe92016-05-11 20:37:46 +00003201 continue;
John McCalla0296f72010-03-19 07:35:19 +00003202
Richard Smithc2bebe92016-05-11 20:37:46 +00003203 bool Usable = !Info.Constructor->isInvalidDecl();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003204 if (ListInitializing)
Richard Smithc2bebe92016-05-11 20:37:46 +00003205 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003206 else
Richard Smithc2bebe92016-05-11 20:37:46 +00003207 Usable = Usable &&
3208 Info.Constructor->isConvertingConstructor(AllowExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003209 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003210 bool SuppressUserConversions = !ConstructorsOnly;
3211 if (SuppressUserConversions && ListInitializing) {
3212 SuppressUserConversions = false;
3213 if (NumArgs == 1) {
3214 // If the first argument is (a reference to) the target type,
3215 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003216 SuppressUserConversions = isFirstArgumentCompatibleWithType(
Richard Smithc2bebe92016-05-11 20:37:46 +00003217 S.Context, Info.Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003218 }
3219 }
Richard Smithc2bebe92016-05-11 20:37:46 +00003220 if (Info.ConstructorTmpl)
3221 S.AddTemplateOverloadCandidate(
3222 Info.ConstructorTmpl, Info.FoundDecl,
3223 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3224 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003225 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003226 // Allow one user-defined conversion when user specifies a
3227 // From->ToType conversion via an static cast (c-style, etc).
Richard Smithc2bebe92016-05-11 20:37:46 +00003228 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003229 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003230 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003231 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003232 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003233 }
3234 }
3235
Douglas Gregor5ab11652010-04-17 22:01:05 +00003236 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003237 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003238 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003239 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003240 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003241 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003242 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003243 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3244 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003245 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3246 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003247 DeclAccessPair FoundDecl = I.getPair();
3248 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003249 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3250 if (isa<UsingShadowDecl>(D))
3251 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3252
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003253 CXXConversionDecl *Conv;
3254 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003255 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3256 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003257 else
John McCallda4458e2010-03-31 01:36:47 +00003258 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003259
3260 if (AllowExplicit || !Conv->isExplicit()) {
3261 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003262 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3263 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003264 CandidateSet,
3265 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003266 else
John McCall5c32be02010-08-24 20:38:10 +00003267 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003268 From, ToType, CandidateSet,
3269 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003270 }
3271 }
3272 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003273 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003274
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003275 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3276
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003277 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003278 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3279 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003280 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003281 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003282 // Record the standard conversion we used and the conversion function.
3283 if (CXXConstructorDecl *Constructor
3284 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3285 // C++ [over.ics.user]p1:
3286 // If the user-defined conversion is specified by a
3287 // constructor (12.3.1), the initial standard conversion
3288 // sequence converts the source type to the type required by
3289 // the argument of the constructor.
3290 //
3291 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003292 if (isa<InitListExpr>(From)) {
3293 // Initializer lists don't have conversions as such.
3294 User.Before.setAsIdentityConversion();
3295 } else {
3296 if (Best->Conversions[0].isEllipsis())
3297 User.EllipsisConversion = true;
3298 else {
3299 User.Before = Best->Conversions[0].Standard;
3300 User.EllipsisConversion = false;
3301 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003302 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003303 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003304 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003305 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003306 User.After.setAsIdentityConversion();
3307 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3308 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003309 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003310 }
3311 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003312 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3313 // C++ [over.ics.user]p1:
3314 //
3315 // [...] If the user-defined conversion is specified by a
3316 // conversion function (12.3.2), the initial standard
3317 // conversion sequence converts the source type to the
3318 // implicit object parameter of the conversion function.
3319 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003320 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003321 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003322 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003323 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003324
John McCall5c32be02010-08-24 20:38:10 +00003325 // C++ [over.ics.user]p2:
3326 // The second standard conversion sequence converts the
3327 // result of the user-defined conversion to the target type
3328 // for the sequence. Since an implicit conversion sequence
3329 // is an initialization, the special rules for
3330 // initialization by user-defined conversion apply when
3331 // selecting the best user-defined conversion for a
3332 // user-defined conversion sequence (see 13.3.3 and
3333 // 13.3.3.1).
3334 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003335 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003336 }
David Blaikie8a40f702012-01-17 06:56:22 +00003337 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003338
John McCall5c32be02010-08-24 20:38:10 +00003339 case OR_No_Viable_Function:
3340 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341
John McCall5c32be02010-08-24 20:38:10 +00003342 case OR_Ambiguous:
3343 return OR_Ambiguous;
3344 }
3345
David Blaikie8a40f702012-01-17 06:56:22 +00003346 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003347}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003348
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003349bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003350Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003351 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003352 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3353 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003354 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003355 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003356 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003357 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003358 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3359 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003360 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003361 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003362 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003363 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003364 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003365 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003366 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003367 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003368 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003369 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003370}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003371
Douglas Gregor2837aa22012-02-22 17:32:19 +00003372/// \brief Compare the user-defined conversion functions or constructors
3373/// of two user-defined conversion sequences to determine whether any ordering
3374/// is possible.
3375static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003376compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003377 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003378 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003379 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003380
Douglas Gregor2837aa22012-02-22 17:32:19 +00003381 // Objective-C++:
3382 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003383 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003384 // respectively, always prefer the conversion to a function pointer,
3385 // because the function pointer is more lightweight and is more likely
3386 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003387 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003388 if (!Conv1)
3389 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003390
Douglas Gregor2837aa22012-02-22 17:32:19 +00003391 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3392 if (!Conv2)
3393 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003394
Douglas Gregor2837aa22012-02-22 17:32:19 +00003395 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3396 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3397 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3398 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003399 return Block1 ? ImplicitConversionSequence::Worse
3400 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003401 }
3402
3403 return ImplicitConversionSequence::Indistinguishable;
3404}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003405
3406static bool hasDeprecatedStringLiteralToCharPtrConversion(
3407 const ImplicitConversionSequence &ICS) {
3408 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3409 (ICS.isUserDefined() &&
3410 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3411}
3412
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003413/// CompareImplicitConversionSequences - Compare two implicit
3414/// conversion sequences to determine whether one is better than the
3415/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003416static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003417CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003418 const ImplicitConversionSequence& ICS1,
3419 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003420{
3421 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3422 // conversion sequences (as defined in 13.3.3.1)
3423 // -- a standard conversion sequence (13.3.3.1.1) is a better
3424 // conversion sequence than a user-defined conversion sequence or
3425 // an ellipsis conversion sequence, and
3426 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3427 // conversion sequence than an ellipsis conversion sequence
3428 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003429 //
John McCall0d1da222010-01-12 00:44:57 +00003430 // C++0x [over.best.ics]p10:
3431 // For the purpose of ranking implicit conversion sequences as
3432 // described in 13.3.3.2, the ambiguous conversion sequence is
3433 // treated as a user-defined sequence that is indistinguishable
3434 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003435
3436 // String literal to 'char *' conversion has been deprecated in C++03. It has
3437 // been removed from C++11. We still accept this conversion, if it happens at
3438 // the best viable function. Otherwise, this conversion is considered worse
3439 // than ellipsis conversion. Consider this as an extension; this is not in the
3440 // standard. For example:
3441 //
3442 // int &f(...); // #1
3443 // void f(char*); // #2
3444 // void g() { int &r = f("foo"); }
3445 //
3446 // In C++03, we pick #2 as the best viable function.
3447 // In C++11, we pick #1 as the best viable function, because ellipsis
3448 // conversion is better than string-literal to char* conversion (since there
3449 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3450 // convert arguments, #2 would be the best viable function in C++11.
3451 // If the best viable function has this conversion, a warning will be issued
3452 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3453
3454 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3455 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3456 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3457 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3458 ? ImplicitConversionSequence::Worse
3459 : ImplicitConversionSequence::Better;
3460
Douglas Gregor5ab11652010-04-17 22:01:05 +00003461 if (ICS1.getKindRank() < ICS2.getKindRank())
3462 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003463 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003464 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003465
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003466 // The following checks require both conversion sequences to be of
3467 // the same kind.
3468 if (ICS1.getKind() != ICS2.getKind())
3469 return ImplicitConversionSequence::Indistinguishable;
3470
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003471 ImplicitConversionSequence::CompareKind Result =
3472 ImplicitConversionSequence::Indistinguishable;
3473
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003474 // Two implicit conversion sequences of the same form are
3475 // indistinguishable conversion sequences unless one of the
3476 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003477
3478 // List-initialization sequence L1 is a better conversion sequence than
3479 // list-initialization sequence L2 if:
3480 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3481 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003482 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003483 // and N1 is smaller than N2.,
3484 // even if one of the other rules in this paragraph would otherwise apply.
3485 if (!ICS1.isBad()) {
3486 if (ICS1.isStdInitializerListElement() &&
3487 !ICS2.isStdInitializerListElement())
3488 return ImplicitConversionSequence::Better;
3489 if (!ICS1.isStdInitializerListElement() &&
3490 ICS2.isStdInitializerListElement())
3491 return ImplicitConversionSequence::Worse;
3492 }
3493
John McCall0d1da222010-01-12 00:44:57 +00003494 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003495 // Standard conversion sequence S1 is a better conversion sequence than
3496 // standard conversion sequence S2 if [...]
Richard Smith0f59cb32015-12-18 21:45:41 +00003497 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003498 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003499 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003500 // User-defined conversion sequence U1 is a better conversion
3501 // sequence than another user-defined conversion sequence U2 if
3502 // they contain the same user-defined conversion function or
3503 // constructor and if the second standard conversion sequence of
3504 // U1 is better than the second standard conversion sequence of
3505 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003506 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003507 ICS2.UserDefined.ConversionFunction)
Richard Smith0f59cb32015-12-18 21:45:41 +00003508 Result = CompareStandardConversionSequences(S, Loc,
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003509 ICS1.UserDefined.After,
3510 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003511 else
3512 Result = compareConversionFunctions(S,
3513 ICS1.UserDefined.ConversionFunction,
3514 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003515 }
3516
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003517 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003518}
3519
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003520static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3521 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3522 Qualifiers Quals;
3523 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003525 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003526
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003527 return Context.hasSameUnqualifiedType(T1, T2);
3528}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003530// Per 13.3.3.2p3, compare the given standard conversion sequences to
3531// determine if one is a proper subset of the other.
3532static ImplicitConversionSequence::CompareKind
3533compareStandardConversionSubsets(ASTContext &Context,
3534 const StandardConversionSequence& SCS1,
3535 const StandardConversionSequence& SCS2) {
3536 ImplicitConversionSequence::CompareKind Result
3537 = ImplicitConversionSequence::Indistinguishable;
3538
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003540 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003541 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3542 return ImplicitConversionSequence::Better;
3543 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3544 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003545
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003546 if (SCS1.Second != SCS2.Second) {
3547 if (SCS1.Second == ICK_Identity)
3548 Result = ImplicitConversionSequence::Better;
3549 else if (SCS2.Second == ICK_Identity)
3550 Result = ImplicitConversionSequence::Worse;
3551 else
3552 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003553 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003554 return ImplicitConversionSequence::Indistinguishable;
3555
3556 if (SCS1.Third == SCS2.Third) {
3557 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3558 : ImplicitConversionSequence::Indistinguishable;
3559 }
3560
3561 if (SCS1.Third == ICK_Identity)
3562 return Result == ImplicitConversionSequence::Worse
3563 ? ImplicitConversionSequence::Indistinguishable
3564 : ImplicitConversionSequence::Better;
3565
3566 if (SCS2.Third == ICK_Identity)
3567 return Result == ImplicitConversionSequence::Better
3568 ? ImplicitConversionSequence::Indistinguishable
3569 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003570
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003571 return ImplicitConversionSequence::Indistinguishable;
3572}
3573
Douglas Gregore696ebb2011-01-26 14:52:12 +00003574/// \brief Determine whether one of the given reference bindings is better
3575/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003576static bool
3577isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3578 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003579 // C++0x [over.ics.rank]p3b4:
3580 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3581 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003582 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003583 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003584 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003585 // reference*.
3586 //
3587 // FIXME: Rvalue references. We're going rogue with the above edits,
3588 // because the semantics in the current C++0x working paper (N3225 at the
3589 // time of this writing) break the standard definition of std::forward
3590 // and std::reference_wrapper when dealing with references to functions.
3591 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003592 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3593 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3594 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003595
Douglas Gregore696ebb2011-01-26 14:52:12 +00003596 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3597 SCS2.IsLvalueReference) ||
3598 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003599 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003600}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003601
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003602/// CompareStandardConversionSequences - Compare two standard
3603/// conversion sequences to determine whether one is better than the
3604/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003605static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003606CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003607 const StandardConversionSequence& SCS1,
3608 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003609{
3610 // Standard conversion sequence S1 is a better conversion sequence
3611 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3612
3613 // -- S1 is a proper subsequence of S2 (comparing the conversion
3614 // sequences in the canonical form defined by 13.3.3.1.1,
3615 // excluding any Lvalue Transformation; the identity conversion
3616 // sequence is considered to be a subsequence of any
3617 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003618 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003619 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003620 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003621
3622 // -- the rank of S1 is better than the rank of S2 (by the rules
3623 // defined below), or, if not that,
3624 ImplicitConversionRank Rank1 = SCS1.getRank();
3625 ImplicitConversionRank Rank2 = SCS2.getRank();
3626 if (Rank1 < Rank2)
3627 return ImplicitConversionSequence::Better;
3628 else if (Rank2 < Rank1)
3629 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003630
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003631 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3632 // are indistinguishable unless one of the following rules
3633 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003634
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003635 // A conversion that is not a conversion of a pointer, or
3636 // pointer to member, to bool is better than another conversion
3637 // that is such a conversion.
3638 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3639 return SCS2.isPointerConversionToBool()
3640 ? ImplicitConversionSequence::Better
3641 : ImplicitConversionSequence::Worse;
3642
Douglas Gregor5c407d92008-10-23 00:40:37 +00003643 // C++ [over.ics.rank]p4b2:
3644 //
3645 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003646 // conversion of B* to A* is better than conversion of B* to
3647 // void*, and conversion of A* to void* is better than conversion
3648 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003649 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003650 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003651 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003652 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003653 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3654 // Exactly one of the conversion sequences is a conversion to
3655 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003656 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3657 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003658 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3659 // Neither conversion sequence converts to a void pointer; compare
3660 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003661 if (ImplicitConversionSequence::CompareKind DerivedCK
Richard Smith0f59cb32015-12-18 21:45:41 +00003662 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003663 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003664 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3665 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003666 // Both conversion sequences are conversions to void
3667 // pointers. Compare the source types to determine if there's an
3668 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003669 QualType FromType1 = SCS1.getFromType();
3670 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003671
3672 // Adjust the types we're converting from via the array-to-pointer
3673 // conversion, if we need to.
3674 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003675 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003676 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003677 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003678
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003679 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3680 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003681
Richard Smith0f59cb32015-12-18 21:45:41 +00003682 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003683 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003684 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003685 return ImplicitConversionSequence::Worse;
3686
3687 // Objective-C++: If one interface is more specific than the
3688 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003689 const ObjCObjectPointerType* FromObjCPtr1
3690 = FromType1->getAs<ObjCObjectPointerType>();
3691 const ObjCObjectPointerType* FromObjCPtr2
3692 = FromType2->getAs<ObjCObjectPointerType>();
3693 if (FromObjCPtr1 && FromObjCPtr2) {
3694 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3695 FromObjCPtr2);
3696 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3697 FromObjCPtr1);
3698 if (AssignLeft != AssignRight) {
3699 return AssignLeft? ImplicitConversionSequence::Better
3700 : ImplicitConversionSequence::Worse;
3701 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003702 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003703 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003704
3705 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3706 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003707 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003708 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003709 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003710
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003711 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003712 // Check for a better reference binding based on the kind of bindings.
3713 if (isBetterReferenceBindingKind(SCS1, SCS2))
3714 return ImplicitConversionSequence::Better;
3715 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3716 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003717
Sebastian Redlb28b4072009-03-22 23:49:27 +00003718 // C++ [over.ics.rank]p3b4:
3719 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3720 // which the references refer are the same type except for
3721 // top-level cv-qualifiers, and the type to which the reference
3722 // initialized by S2 refers is more cv-qualified than the type
3723 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003724 QualType T1 = SCS1.getToType(2);
3725 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003726 T1 = S.Context.getCanonicalType(T1);
3727 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003728 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003729 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3730 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003731 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003732 // Objective-C++ ARC: If the references refer to objects with different
3733 // lifetimes, prefer bindings that don't change lifetime.
3734 if (SCS1.ObjCLifetimeConversionBinding !=
3735 SCS2.ObjCLifetimeConversionBinding) {
3736 return SCS1.ObjCLifetimeConversionBinding
3737 ? ImplicitConversionSequence::Worse
3738 : ImplicitConversionSequence::Better;
3739 }
3740
Chandler Carruth8e543b32010-12-12 08:17:55 +00003741 // If the type is an array type, promote the element qualifiers to the
3742 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003743 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003744 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003745 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003746 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003747 if (T2.isMoreQualifiedThan(T1))
3748 return ImplicitConversionSequence::Better;
3749 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003750 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003751 }
3752 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003753
Francois Pichet08d2fa02011-09-18 21:37:37 +00003754 // In Microsoft mode, prefer an integral conversion to a
3755 // floating-to-integral conversion if the integral conversion
3756 // is between types of the same size.
3757 // For example:
3758 // void f(float);
3759 // void f(int);
3760 // int main {
3761 // long a;
3762 // f(a);
3763 // }
3764 // Here, MSVC will call f(int) instead of generating a compile error
3765 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003766 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3767 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003768 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003769 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003770 return ImplicitConversionSequence::Better;
3771
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003772 return ImplicitConversionSequence::Indistinguishable;
3773}
3774
3775/// CompareQualificationConversions - Compares two standard conversion
3776/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003777/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003778static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003779CompareQualificationConversions(Sema &S,
3780 const StandardConversionSequence& SCS1,
3781 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003782 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003783 // -- S1 and S2 differ only in their qualification conversion and
3784 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3785 // cv-qualification signature of type T1 is a proper subset of
3786 // the cv-qualification signature of type T2, and S1 is not the
3787 // deprecated string literal array-to-pointer conversion (4.2).
3788 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3789 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3790 return ImplicitConversionSequence::Indistinguishable;
3791
3792 // FIXME: the example in the standard doesn't use a qualification
3793 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003794 QualType T1 = SCS1.getToType(2);
3795 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003796 T1 = S.Context.getCanonicalType(T1);
3797 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003798 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003799 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3800 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003801
3802 // If the types are the same, we won't learn anything by unwrapped
3803 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003804 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003805 return ImplicitConversionSequence::Indistinguishable;
3806
Chandler Carruth607f38e2009-12-29 07:16:59 +00003807 // If the type is an array type, promote the element qualifiers to the type
3808 // for comparison.
3809 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003810 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003811 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003812 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003813
Mike Stump11289f42009-09-09 15:08:12 +00003814 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003815 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003816
3817 // Objective-C++ ARC:
3818 // Prefer qualification conversions not involving a change in lifetime
3819 // to qualification conversions that do not change lifetime.
3820 if (SCS1.QualificationIncludesObjCLifetime !=
3821 SCS2.QualificationIncludesObjCLifetime) {
3822 Result = SCS1.QualificationIncludesObjCLifetime
3823 ? ImplicitConversionSequence::Worse
3824 : ImplicitConversionSequence::Better;
3825 }
3826
John McCall5c32be02010-08-24 20:38:10 +00003827 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003828 // Within each iteration of the loop, we check the qualifiers to
3829 // determine if this still looks like a qualification
3830 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003831 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003832 // until there are no more pointers or pointers-to-members left
3833 // to unwrap. This essentially mimics what
3834 // IsQualificationConversion does, but here we're checking for a
3835 // strict subset of qualifiers.
3836 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3837 // The qualifiers are the same, so this doesn't tell us anything
3838 // about how the sequences rank.
3839 ;
3840 else if (T2.isMoreQualifiedThan(T1)) {
3841 // T1 has fewer qualifiers, so it could be the better sequence.
3842 if (Result == ImplicitConversionSequence::Worse)
3843 // Neither has qualifiers that are a subset of the other's
3844 // qualifiers.
3845 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003846
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003847 Result = ImplicitConversionSequence::Better;
3848 } else if (T1.isMoreQualifiedThan(T2)) {
3849 // T2 has fewer qualifiers, so it could be the better sequence.
3850 if (Result == ImplicitConversionSequence::Better)
3851 // Neither has qualifiers that are a subset of the other's
3852 // qualifiers.
3853 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003854
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003855 Result = ImplicitConversionSequence::Worse;
3856 } else {
3857 // Qualifiers are disjoint.
3858 return ImplicitConversionSequence::Indistinguishable;
3859 }
3860
3861 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003862 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003863 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003864 }
3865
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003866 // Check that the winning standard conversion sequence isn't using
3867 // the deprecated string literal array to pointer conversion.
3868 switch (Result) {
3869 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003870 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003871 Result = ImplicitConversionSequence::Indistinguishable;
3872 break;
3873
3874 case ImplicitConversionSequence::Indistinguishable:
3875 break;
3876
3877 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003878 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003879 Result = ImplicitConversionSequence::Indistinguishable;
3880 break;
3881 }
3882
3883 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003884}
3885
Douglas Gregor5c407d92008-10-23 00:40:37 +00003886/// CompareDerivedToBaseConversions - Compares two standard conversion
3887/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003888/// various kinds of derived-to-base conversions (C++
3889/// [over.ics.rank]p4b3). As part of these checks, we also look at
3890/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003891static ImplicitConversionSequence::CompareKind
Richard Smith0f59cb32015-12-18 21:45:41 +00003892CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
John McCall5c32be02010-08-24 20:38:10 +00003893 const StandardConversionSequence& SCS1,
3894 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003895 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003896 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003897 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003898 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003899
3900 // Adjust the types we're converting from via the array-to-pointer
3901 // conversion, if we need to.
3902 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003903 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003904 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003905 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003906
3907 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003908 FromType1 = S.Context.getCanonicalType(FromType1);
3909 ToType1 = S.Context.getCanonicalType(ToType1);
3910 FromType2 = S.Context.getCanonicalType(FromType2);
3911 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003912
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003913 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003914 //
3915 // If class B is derived directly or indirectly from class A and
3916 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003917 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003918 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003919 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003920 SCS2.Second == ICK_Pointer_Conversion &&
3921 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3922 FromType1->isPointerType() && FromType2->isPointerType() &&
3923 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003924 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003925 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003926 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003927 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003928 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003929 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003930 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003931 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003932
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003933 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003934 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003935 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003936 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003937 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003938 return ImplicitConversionSequence::Worse;
3939 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003940
3941 // -- conversion of B* to A* is better than conversion of C* to A*,
3942 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00003943 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003944 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00003945 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003946 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003947 }
3948 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3949 SCS2.Second == ICK_Pointer_Conversion) {
3950 const ObjCObjectPointerType *FromPtr1
3951 = FromType1->getAs<ObjCObjectPointerType>();
3952 const ObjCObjectPointerType *FromPtr2
3953 = FromType2->getAs<ObjCObjectPointerType>();
3954 const ObjCObjectPointerType *ToPtr1
3955 = ToType1->getAs<ObjCObjectPointerType>();
3956 const ObjCObjectPointerType *ToPtr2
3957 = ToType2->getAs<ObjCObjectPointerType>();
3958
3959 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3960 // Apply the same conversion ranking rules for Objective-C pointer types
3961 // that we do for C++ pointers to class types. However, we employ the
3962 // Objective-C pseudo-subtyping relationship used for assignment of
3963 // Objective-C pointer types.
3964 bool FromAssignLeft
3965 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3966 bool FromAssignRight
3967 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3968 bool ToAssignLeft
3969 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3970 bool ToAssignRight
3971 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3972
3973 // A conversion to an a non-id object pointer type or qualified 'id'
3974 // type is better than a conversion to 'id'.
3975 if (ToPtr1->isObjCIdType() &&
3976 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3977 return ImplicitConversionSequence::Worse;
3978 if (ToPtr2->isObjCIdType() &&
3979 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3980 return ImplicitConversionSequence::Better;
3981
3982 // A conversion to a non-id object pointer type is better than a
3983 // conversion to a qualified 'id' type
3984 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3985 return ImplicitConversionSequence::Worse;
3986 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3987 return ImplicitConversionSequence::Better;
3988
3989 // A conversion to an a non-Class object pointer type or qualified 'Class'
3990 // type is better than a conversion to 'Class'.
3991 if (ToPtr1->isObjCClassType() &&
3992 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3993 return ImplicitConversionSequence::Worse;
3994 if (ToPtr2->isObjCClassType() &&
3995 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3996 return ImplicitConversionSequence::Better;
3997
3998 // A conversion to a non-Class object pointer type is better than a
3999 // conversion to a qualified 'Class' type.
4000 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4001 return ImplicitConversionSequence::Worse;
4002 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4003 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00004004
Douglas Gregor058d3de2011-01-31 18:51:41 +00004005 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4006 if (S.Context.hasSameType(FromType1, FromType2) &&
4007 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4008 (ToAssignLeft != ToAssignRight))
4009 return ToAssignLeft? ImplicitConversionSequence::Worse
4010 : ImplicitConversionSequence::Better;
4011
4012 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4013 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4014 (FromAssignLeft != FromAssignRight))
4015 return FromAssignLeft? ImplicitConversionSequence::Better
4016 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004017 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00004018 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00004019
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004020 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004021 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4022 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4023 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004024 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004025 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004026 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004027 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004028 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004029 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004030 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004031 ToType2->getAs<MemberPointerType>();
4032 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4033 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4034 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4035 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4036 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4037 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4038 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4039 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00004040 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004041 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004042 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004043 return ImplicitConversionSequence::Worse;
Richard Smith0f59cb32015-12-18 21:45:41 +00004044 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004045 return ImplicitConversionSequence::Better;
4046 }
4047 // conversion of B::* to C::* is better than conversion of A::* to C::*
4048 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004049 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004050 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004051 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00004052 return ImplicitConversionSequence::Worse;
4053 }
4054 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004055
Douglas Gregor5ab11652010-04-17 22:01:05 +00004056 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00004057 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00004058 // -- binding of an expression of type C to a reference of type
4059 // B& is better than binding an expression of type C to a
4060 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004061 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4062 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004063 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004064 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004065 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004066 return ImplicitConversionSequence::Worse;
4067 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004068
Douglas Gregor2fe98832008-11-03 19:09:14 +00004069 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00004070 // -- binding of an expression of type B to a reference of type
4071 // A& is better than binding an expression of type C to a
4072 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00004073 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4074 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00004075 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004076 return ImplicitConversionSequence::Better;
Richard Smith0f59cb32015-12-18 21:45:41 +00004077 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00004078 return ImplicitConversionSequence::Worse;
4079 }
4080 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004081
Douglas Gregor5c407d92008-10-23 00:40:37 +00004082 return ImplicitConversionSequence::Indistinguishable;
4083}
4084
Douglas Gregor45bb4832013-03-26 23:36:30 +00004085/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4086/// C++ class.
4087static bool isTypeValid(QualType T) {
4088 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4089 return !Record->isInvalidDecl();
4090
4091 return true;
4092}
4093
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004094/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4095/// determine whether they are reference-related,
4096/// reference-compatible, reference-compatible with added
4097/// qualification, or incompatible, for use in C++ initialization by
4098/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4099/// type, and the first type (T1) is the pointee type of the reference
4100/// type being initialized.
4101Sema::ReferenceCompareResult
4102Sema::CompareReferenceRelationship(SourceLocation Loc,
4103 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004104 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004105 bool &ObjCConversion,
4106 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004107 assert(!OrigT1->isReferenceType() &&
4108 "T1 must be the pointee type of the reference type");
4109 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4110
4111 QualType T1 = Context.getCanonicalType(OrigT1);
4112 QualType T2 = Context.getCanonicalType(OrigT2);
4113 Qualifiers T1Quals, T2Quals;
4114 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4115 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4116
4117 // C++ [dcl.init.ref]p4:
4118 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4119 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4120 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004121 DerivedToBase = false;
4122 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004123 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004124 if (UnqualT1 == UnqualT2) {
4125 // Nothing to do.
Richard Smithdb0ac552015-12-18 22:40:25 +00004126 } else if (isCompleteType(Loc, OrigT2) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004127 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004128 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004129 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004130 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4131 UnqualT2->isObjCObjectOrInterfaceType() &&
4132 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4133 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004134 else
4135 return Ref_Incompatible;
4136
4137 // At this point, we know that T1 and T2 are reference-related (at
4138 // least).
4139
4140 // If the type is an array type, promote the element qualifiers to the type
4141 // for comparison.
4142 if (isa<ArrayType>(T1) && T1Quals)
4143 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4144 if (isa<ArrayType>(T2) && T2Quals)
4145 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4146
4147 // C++ [dcl.init.ref]p4:
4148 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4149 // reference-related to T2 and cv1 is the same cv-qualification
4150 // as, or greater cv-qualification than, cv2. For purposes of
4151 // overload resolution, cases for which cv1 is greater
4152 // cv-qualification than cv2 are identified as
4153 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004154 //
4155 // Note that we also require equivalence of Objective-C GC and address-space
4156 // qualifiers when performing these computations, so that e.g., an int in
4157 // address space 1 is not reference-compatible with an int in address
4158 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004159 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4160 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004161 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4162 ObjCLifetimeConversion = true;
4163
John McCall31168b02011-06-15 23:02:42 +00004164 T1Quals.removeObjCLifetime();
4165 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004166 }
4167
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004168 // MS compiler ignores __unaligned qualifier for references; do the same.
4169 T1Quals.removeUnaligned();
4170 T2Quals.removeUnaligned();
4171
Douglas Gregord517d552011-04-28 17:56:11 +00004172 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004173 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004174 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004175 return Ref_Compatible_With_Added_Qualification;
4176 else
4177 return Ref_Related;
4178}
4179
Douglas Gregor836a7e82010-08-11 02:15:33 +00004180/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004181/// with DeclType. Return true if something definite is found.
4182static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004183FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4184 QualType DeclType, SourceLocation DeclLoc,
4185 Expr *Init, QualType T2, bool AllowRvalues,
4186 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004187 assert(T2->isRecordType() && "Can only find conversions of record types.");
4188 CXXRecordDecl *T2RecordDecl
4189 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4190
Richard Smith100b24a2014-04-17 01:52:14 +00004191 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004192 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4193 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004194 NamedDecl *D = *I;
4195 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4196 if (isa<UsingShadowDecl>(D))
4197 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4198
4199 FunctionTemplateDecl *ConvTemplate
4200 = dyn_cast<FunctionTemplateDecl>(D);
4201 CXXConversionDecl *Conv;
4202 if (ConvTemplate)
4203 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4204 else
4205 Conv = cast<CXXConversionDecl>(D);
4206
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004207 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004208 // explicit conversions, skip it.
4209 if (!AllowExplicit && Conv->isExplicit())
4210 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211
Douglas Gregor836a7e82010-08-11 02:15:33 +00004212 if (AllowRvalues) {
4213 bool DerivedToBase = false;
4214 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004215 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004216
4217 // If we are initializing an rvalue reference, don't permit conversion
4218 // functions that return lvalues.
4219 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4220 const ReferenceType *RefType
4221 = Conv->getConversionType()->getAs<LValueReferenceType>();
4222 if (RefType && !RefType->getPointeeType()->isFunctionType())
4223 continue;
4224 }
4225
Douglas Gregor836a7e82010-08-11 02:15:33 +00004226 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004227 S.CompareReferenceRelationship(
4228 DeclLoc,
4229 Conv->getConversionType().getNonReferenceType()
4230 .getUnqualifiedType(),
4231 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004232 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004233 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004234 continue;
4235 } else {
4236 // If the conversion function doesn't return a reference type,
4237 // it can't be considered for this conversion. An rvalue reference
4238 // is only acceptable if its referencee is a function type.
4239
4240 const ReferenceType *RefType =
4241 Conv->getConversionType()->getAs<ReferenceType>();
4242 if (!RefType ||
4243 (!RefType->isLValueReferenceType() &&
4244 !RefType->getPointeeType()->isFunctionType()))
4245 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247
Douglas Gregor836a7e82010-08-11 02:15:33 +00004248 if (ConvTemplate)
4249 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004250 Init, DeclType, CandidateSet,
4251 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004252 else
4253 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004254 DeclType, CandidateSet,
4255 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004256 }
4257
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004258 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4259
Sebastian Redld92badf2010-06-30 18:13:39 +00004260 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004261 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004262 case OR_Success:
4263 // C++ [over.ics.ref]p1:
4264 //
4265 // [...] If the parameter binds directly to the result of
4266 // applying a conversion function to the argument
4267 // expression, the implicit conversion sequence is a
4268 // user-defined conversion sequence (13.3.3.1.2), with the
4269 // second standard conversion sequence either an identity
4270 // conversion or, if the conversion function returns an
4271 // entity of a type that is a derived class of the parameter
4272 // type, a derived-to-base Conversion.
4273 if (!Best->FinalConversion.DirectBinding)
4274 return false;
4275
4276 ICS.setUserDefined();
4277 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4278 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004279 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004280 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004281 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004282 ICS.UserDefined.EllipsisConversion = false;
4283 assert(ICS.UserDefined.After.ReferenceBinding &&
4284 ICS.UserDefined.After.DirectBinding &&
4285 "Expected a direct reference binding!");
4286 return true;
4287
4288 case OR_Ambiguous:
4289 ICS.setAmbiguous();
4290 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4291 Cand != CandidateSet.end(); ++Cand)
4292 if (Cand->Viable)
Richard Smithc2bebe92016-05-11 20:37:46 +00004293 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00004294 return true;
4295
4296 case OR_No_Viable_Function:
4297 case OR_Deleted:
4298 // There was no suitable conversion, or we found a deleted
4299 // conversion; continue with other checks.
4300 return false;
4301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302
David Blaikie8a40f702012-01-17 06:56:22 +00004303 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004304}
4305
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004306/// \brief Compute an implicit conversion sequence for reference
4307/// initialization.
4308static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004309TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004310 SourceLocation DeclLoc,
4311 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004312 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004313 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4314
4315 // Most paths end in a failed conversion.
4316 ImplicitConversionSequence ICS;
4317 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4318
4319 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4320 QualType T2 = Init->getType();
4321
4322 // If the initializer is the address of an overloaded function, try
4323 // to resolve the overloaded function. If all goes well, T2 is the
4324 // type of the resulting function.
4325 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4326 DeclAccessPair Found;
4327 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4328 false, Found))
4329 T2 = Fn->getType();
4330 }
4331
4332 // Compute some basic properties of the types and the initializer.
4333 bool isRValRef = DeclType->isRValueReferenceType();
4334 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004335 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004336 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004337 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004338 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004339 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004340 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004341
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004342
Sebastian Redld92badf2010-06-30 18:13:39 +00004343 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004344 // A reference to type "cv1 T1" is initialized by an expression
4345 // of type "cv2 T2" as follows:
4346
Sebastian Redld92badf2010-06-30 18:13:39 +00004347 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004348 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004349 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4350 // reference-compatible with "cv2 T2," or
4351 //
4352 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4353 if (InitCategory.isLValue() &&
4354 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004355 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004356 // When a parameter of reference type binds directly (8.5.3)
4357 // to an argument expression, the implicit conversion sequence
4358 // is the identity conversion, unless the argument expression
4359 // has a type that is a derived class of the parameter type,
4360 // in which case the implicit conversion sequence is a
4361 // derived-to-base Conversion (13.3.3.1).
4362 ICS.setStandard();
4363 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004364 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4365 : ObjCConversion? ICK_Compatible_Conversion
4366 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004367 ICS.Standard.Third = ICK_Identity;
4368 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4369 ICS.Standard.setToType(0, T2);
4370 ICS.Standard.setToType(1, T1);
4371 ICS.Standard.setToType(2, T1);
4372 ICS.Standard.ReferenceBinding = true;
4373 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004374 ICS.Standard.IsLvalueReference = !isRValRef;
4375 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4376 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004377 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004378 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004379 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004380 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004381
Sebastian Redld92badf2010-06-30 18:13:39 +00004382 // Nothing more to do: the inaccessibility/ambiguity check for
4383 // derived-to-base conversions is suppressed when we're
4384 // computing the implicit conversion sequence (C++
4385 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004386 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004387 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004388
Sebastian Redld92badf2010-06-30 18:13:39 +00004389 // -- has a class type (i.e., T2 is a class type), where T1 is
4390 // not reference-related to T2, and can be implicitly
4391 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4392 // is reference-compatible with "cv3 T3" 92) (this
4393 // conversion is selected by enumerating the applicable
4394 // conversion functions (13.3.1.6) and choosing the best
4395 // one through overload resolution (13.3)),
4396 if (!SuppressUserConversions && T2->isRecordType() &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004397 S.isCompleteType(DeclLoc, T2) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004398 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004399 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4400 Init, T2, /*AllowRvalues=*/false,
4401 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004402 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004403 }
4404 }
4405
Sebastian Redld92badf2010-06-30 18:13:39 +00004406 // -- Otherwise, the reference shall be an lvalue reference to a
4407 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004408 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004409 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004410 return ICS;
4411
Douglas Gregorf143cd52011-01-24 16:14:37 +00004412 // -- If the initializer expression
4413 //
4414 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004415 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004416 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4417 (InitCategory.isXValue() ||
4418 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4419 (InitCategory.isLValue() && T2->isFunctionType()))) {
4420 ICS.setStandard();
4421 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004423 : ObjCConversion? ICK_Compatible_Conversion
4424 : ICK_Identity;
4425 ICS.Standard.Third = ICK_Identity;
4426 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4427 ICS.Standard.setToType(0, T2);
4428 ICS.Standard.setToType(1, T1);
4429 ICS.Standard.setToType(2, T1);
4430 ICS.Standard.ReferenceBinding = true;
4431 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4432 // binding unless we're binding to a class prvalue.
4433 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4434 // allow the use of rvalue references in C++98/03 for the benefit of
4435 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004436 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004437 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004438 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004439 ICS.Standard.IsLvalueReference = !isRValRef;
4440 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004441 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004442 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004443 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004444 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004445 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004447 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004448
Douglas Gregorf143cd52011-01-24 16:14:37 +00004449 // -- has a class type (i.e., T2 is a class type), where T1 is not
4450 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004451 // an xvalue, class prvalue, or function lvalue of type
4452 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004453 // "cv3 T3",
4454 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004455 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004456 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004457 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004458 // class subobject).
4459 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
Richard Smithdb0ac552015-12-18 22:40:25 +00004460 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004461 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4462 Init, T2, /*AllowRvalues=*/true,
4463 AllowExplicit)) {
4464 // In the second case, if the reference is an rvalue reference
4465 // and the second standard conversion sequence of the
4466 // user-defined conversion sequence includes an lvalue-to-rvalue
4467 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004469 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4470 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4471
Douglas Gregor95273c32011-01-21 16:36:05 +00004472 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004473 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004474
Richard Smith19172c42014-07-14 02:28:44 +00004475 // A temporary of function type cannot be created; don't even try.
4476 if (T1->isFunctionType())
4477 return ICS;
4478
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004479 // -- Otherwise, a temporary of type "cv1 T1" is created and
4480 // initialized from the initializer expression using the
4481 // rules for a non-reference copy initialization (8.5). The
4482 // reference is then bound to the temporary. If T1 is
4483 // reference-related to T2, cv1 must be the same
4484 // cv-qualification as, or greater cv-qualification than,
4485 // cv2; otherwise, the program is ill-formed.
4486 if (RefRelationship == Sema::Ref_Related) {
4487 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4488 // we would be reference-compatible or reference-compatible with
4489 // added qualification. But that wasn't the case, so the reference
4490 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004491 //
4492 // Note that we only want to check address spaces and cvr-qualifiers here.
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004493 // ObjC GC, lifetime and unaligned qualifiers aren't important.
John McCall31168b02011-06-15 23:02:42 +00004494 Qualifiers T1Quals = T1.getQualifiers();
4495 Qualifiers T2Quals = T2.getQualifiers();
4496 T1Quals.removeObjCGCAttr();
4497 T1Quals.removeObjCLifetime();
4498 T2Quals.removeObjCGCAttr();
4499 T2Quals.removeObjCLifetime();
Andrey Bokhanko45d41322016-05-11 18:38:21 +00004500 // MS compiler ignores __unaligned qualifier for references; do the same.
4501 T1Quals.removeUnaligned();
4502 T2Quals.removeUnaligned();
John McCall31168b02011-06-15 23:02:42 +00004503 if (!T1Quals.compatiblyIncludes(T2Quals))
4504 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004505 }
4506
4507 // If at least one of the types is a class type, the types are not
4508 // related, and we aren't allowed any user conversions, the
4509 // reference binding fails. This case is important for breaking
4510 // recursion, since TryImplicitConversion below will attempt to
4511 // create a temporary through the use of a copy constructor.
4512 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4513 (T1->isRecordType() || T2->isRecordType()))
4514 return ICS;
4515
Douglas Gregorcba72b12011-01-21 05:18:22 +00004516 // If T1 is reference-related to T2 and the reference is an rvalue
4517 // reference, the initializer expression shall not be an lvalue.
4518 if (RefRelationship >= Sema::Ref_Related &&
4519 isRValRef && Init->Classify(S.Context).isLValue())
4520 return ICS;
4521
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004522 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004523 // When a parameter of reference type is not bound directly to
4524 // an argument expression, the conversion sequence is the one
4525 // required to convert the argument expression to the
4526 // underlying type of the reference according to
4527 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4528 // to copy-initializing a temporary of the underlying type with
4529 // the argument expression. Any difference in top-level
4530 // cv-qualification is subsumed by the initialization itself
4531 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004532 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4533 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004534 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004535 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004536 /*AllowObjCWritebackConversion=*/false,
4537 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004538
4539 // Of course, that's still a reference binding.
4540 if (ICS.isStandard()) {
4541 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004542 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004543 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004544 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004545 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004546 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004547 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004548 const ReferenceType *LValRefType =
4549 ICS.UserDefined.ConversionFunction->getReturnType()
4550 ->getAs<LValueReferenceType>();
4551
4552 // C++ [over.ics.ref]p3:
4553 // Except for an implicit object parameter, for which see 13.3.1, a
4554 // standard conversion sequence cannot be formed if it requires [...]
4555 // binding an rvalue reference to an lvalue other than a function
4556 // lvalue.
4557 // Note that the function case is not possible here.
4558 if (DeclType->isRValueReferenceType() && LValRefType) {
4559 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4560 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4561 // reference to an rvalue!
4562 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4563 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004564 }
Richard Smith19172c42014-07-14 02:28:44 +00004565
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004566 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004567 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004568 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4569 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004570 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4571 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004572 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004573
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004574 return ICS;
4575}
4576
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004577static ImplicitConversionSequence
4578TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4579 bool SuppressUserConversions,
4580 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004581 bool AllowObjCWritebackConversion,
4582 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004583
4584/// TryListConversion - Try to copy-initialize a value of type ToType from the
4585/// initializer list From.
4586static ImplicitConversionSequence
4587TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4588 bool SuppressUserConversions,
4589 bool InOverloadResolution,
4590 bool AllowObjCWritebackConversion) {
4591 // C++11 [over.ics.list]p1:
4592 // When an argument is an initializer list, it is not an expression and
4593 // special rules apply for converting it to a parameter type.
4594
4595 ImplicitConversionSequence Result;
4596 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4597
Sebastian Redl09edce02012-01-23 22:09:39 +00004598 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004599 // initialized from init lists.
Richard Smithdb0ac552015-12-18 22:40:25 +00004600 if (!S.isCompleteType(From->getLocStart(), ToType))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004601 return Result;
4602
Larisse Voufo19d08672015-01-27 18:47:05 +00004603 // Per DR1467:
4604 // If the parameter type is a class X and the initializer list has a single
4605 // element of type cv U, where U is X or a class derived from X, the
4606 // implicit conversion sequence is the one required to convert the element
4607 // to the parameter type.
4608 //
4609 // Otherwise, if the parameter type is a character array [... ]
4610 // and the initializer list has a single element that is an
4611 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4612 // implicit conversion sequence is the identity conversion.
4613 if (From->getNumInits() == 1) {
4614 if (ToType->isRecordType()) {
4615 QualType InitType = From->getInit(0)->getType();
4616 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004617 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
Larisse Voufo19d08672015-01-27 18:47:05 +00004618 return TryCopyInitialization(S, From->getInit(0), ToType,
4619 SuppressUserConversions,
4620 InOverloadResolution,
4621 AllowObjCWritebackConversion);
4622 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004623 // FIXME: Check the other conditions here: array of character type,
4624 // initializer is a string literal.
4625 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004626 InitializedEntity Entity =
4627 InitializedEntity::InitializeParameter(S.Context, ToType,
4628 /*Consumed=*/false);
4629 if (S.CanPerformCopyInitialization(Entity, From)) {
4630 Result.setStandard();
4631 Result.Standard.setAsIdentityConversion();
4632 Result.Standard.setFromType(ToType);
4633 Result.Standard.setAllToTypes(ToType);
4634 return Result;
4635 }
4636 }
4637 }
4638
4639 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004640 // C++11 [over.ics.list]p2:
4641 // If the parameter type is std::initializer_list<X> or "array of X" and
4642 // all the elements can be implicitly converted to X, the implicit
4643 // conversion sequence is the worst conversion necessary to convert an
4644 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004645 //
4646 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004647 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004648 // list has exactly N elements or if it has fewer than N elements and X is
4649 // default-constructible, and if all the elements of the initializer list
4650 // can be implicitly converted to X, the implicit conversion sequence is
4651 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004652 //
4653 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004654 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004655 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004656 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004657 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004658 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004659 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004660 if (!X.isNull()) {
4661 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4662 Expr *Init = From->getInit(i);
4663 ImplicitConversionSequence ICS =
4664 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4665 InOverloadResolution,
4666 AllowObjCWritebackConversion);
4667 // If a single element isn't convertible, fail.
4668 if (ICS.isBad()) {
4669 Result = ICS;
4670 break;
4671 }
4672 // Otherwise, look for the worst conversion.
4673 if (Result.isBad() ||
Richard Smith0f59cb32015-12-18 21:45:41 +00004674 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4675 Result) ==
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004676 ImplicitConversionSequence::Worse)
4677 Result = ICS;
4678 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004679
4680 // For an empty list, we won't have computed any conversion sequence.
4681 // Introduce the identity conversion sequence.
4682 if (From->getNumInits() == 0) {
4683 Result.setStandard();
4684 Result.Standard.setAsIdentityConversion();
4685 Result.Standard.setFromType(ToType);
4686 Result.Standard.setAllToTypes(ToType);
4687 }
4688
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004689 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004690 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004691 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004692
Larisse Voufo19d08672015-01-27 18:47:05 +00004693 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004694 // C++11 [over.ics.list]p3:
4695 // Otherwise, if the parameter is a non-aggregate class X and overload
4696 // resolution chooses a single best constructor [...] the implicit
4697 // conversion sequence is a user-defined conversion sequence. If multiple
4698 // constructors are viable but none is better than the others, the
4699 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004700 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4701 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004702 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4703 /*AllowExplicit=*/false,
4704 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004705 AllowObjCWritebackConversion,
4706 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004707 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004708
Larisse Voufo19d08672015-01-27 18:47:05 +00004709 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004710 // C++11 [over.ics.list]p4:
4711 // Otherwise, if the parameter has an aggregate type which can be
4712 // initialized from the initializer list [...] the implicit conversion
4713 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004714 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004715 // Type is an aggregate, argument is an init list. At this point it comes
4716 // down to checking whether the initialization works.
4717 // FIXME: Find out whether this parameter is consumed or not.
4718 InitializedEntity Entity =
4719 InitializedEntity::InitializeParameter(S.Context, ToType,
4720 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004721 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004722 Result.setUserDefined();
4723 Result.UserDefined.Before.setAsIdentityConversion();
4724 // Initializer lists don't have a type.
4725 Result.UserDefined.Before.setFromType(QualType());
4726 Result.UserDefined.Before.setAllToTypes(QualType());
4727
4728 Result.UserDefined.After.setAsIdentityConversion();
4729 Result.UserDefined.After.setFromType(ToType);
4730 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004731 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004732 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004733 return Result;
4734 }
4735
Larisse Voufo19d08672015-01-27 18:47:05 +00004736 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004737 // C++11 [over.ics.list]p5:
4738 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004739 if (ToType->isReferenceType()) {
4740 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4741 // mention initializer lists in any way. So we go by what list-
4742 // initialization would do and try to extrapolate from that.
4743
4744 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4745
4746 // If the initializer list has a single element that is reference-related
4747 // to the parameter type, we initialize the reference from that.
4748 if (From->getNumInits() == 1) {
4749 Expr *Init = From->getInit(0);
4750
4751 QualType T2 = Init->getType();
4752
4753 // If the initializer is the address of an overloaded function, try
4754 // to resolve the overloaded function. If all goes well, T2 is the
4755 // type of the resulting function.
4756 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4757 DeclAccessPair Found;
4758 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4759 Init, ToType, false, Found))
4760 T2 = Fn->getType();
4761 }
4762
4763 // Compute some basic properties of the types and the initializer.
4764 bool dummy1 = false;
4765 bool dummy2 = false;
4766 bool dummy3 = false;
4767 Sema::ReferenceCompareResult RefRelationship
4768 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4769 dummy2, dummy3);
4770
Richard Smith4d2bbd72013-09-06 01:22:42 +00004771 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004772 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4773 SuppressUserConversions,
4774 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004775 }
Sebastian Redldf888642011-12-03 14:54:30 +00004776 }
4777
4778 // Otherwise, we bind the reference to a temporary created from the
4779 // initializer list.
4780 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4781 InOverloadResolution,
4782 AllowObjCWritebackConversion);
4783 if (Result.isFailure())
4784 return Result;
4785 assert(!Result.isEllipsis() &&
4786 "Sub-initialization cannot result in ellipsis conversion.");
4787
4788 // Can we even bind to a temporary?
4789 if (ToType->isRValueReferenceType() ||
4790 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4791 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4792 Result.UserDefined.After;
4793 SCS.ReferenceBinding = true;
4794 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4795 SCS.BindsToRvalue = true;
4796 SCS.BindsToFunctionLvalue = false;
4797 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4798 SCS.ObjCLifetimeConversionBinding = false;
4799 } else
4800 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4801 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004802 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004803 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004804
Larisse Voufo19d08672015-01-27 18:47:05 +00004805 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004806 // C++11 [over.ics.list]p6:
4807 // Otherwise, if the parameter type is not a class:
4808 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004809 // - if the initializer list has one element that is not itself an
4810 // initializer list, the implicit conversion sequence is the one
4811 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004812 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004813 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004814 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4815 SuppressUserConversions,
4816 InOverloadResolution,
4817 AllowObjCWritebackConversion);
4818 // - if the initializer list has no elements, the implicit conversion
4819 // sequence is the identity conversion.
4820 else if (NumInits == 0) {
4821 Result.setStandard();
4822 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004823 Result.Standard.setFromType(ToType);
4824 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004825 }
4826 return Result;
4827 }
4828
Larisse Voufo19d08672015-01-27 18:47:05 +00004829 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004830 // C++11 [over.ics.list]p7:
4831 // In all cases other than those enumerated above, no conversion is possible
4832 return Result;
4833}
4834
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004835/// TryCopyInitialization - Try to copy-initialize a value of type
4836/// ToType from the expression From. Return the implicit conversion
4837/// sequence required to pass this argument, which may be a bad
4838/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004839/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004840/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004841static ImplicitConversionSequence
4842TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004843 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004844 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004845 bool AllowObjCWritebackConversion,
4846 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004847 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4848 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4849 InOverloadResolution,AllowObjCWritebackConversion);
4850
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004851 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004852 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004853 /*FIXME:*/From->getLocStart(),
4854 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004855 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004856
John McCall5c32be02010-08-24 20:38:10 +00004857 return TryImplicitConversion(S, From, ToType,
4858 SuppressUserConversions,
4859 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004860 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004861 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004862 AllowObjCWritebackConversion,
4863 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004864}
4865
Anna Zaks1b068122011-07-28 19:46:48 +00004866static bool TryCopyInitialization(const CanQualType FromQTy,
4867 const CanQualType ToQTy,
4868 Sema &S,
4869 SourceLocation Loc,
4870 ExprValueKind FromVK) {
4871 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4872 ImplicitConversionSequence ICS =
4873 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4874
4875 return !ICS.isBad();
4876}
4877
Douglas Gregor436424c2008-11-18 23:14:02 +00004878/// TryObjectArgumentInitialization - Try to initialize the object
4879/// parameter of the given member function (@c Method) from the
4880/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004881static ImplicitConversionSequence
Richard Smith0f59cb32015-12-18 21:45:41 +00004882TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004883 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004884 CXXMethodDecl *Method,
4885 CXXRecordDecl *ActingContext) {
4886 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004887 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4888 // const volatile object.
4889 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4890 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004891 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004892
4893 // Set up the conversion sequence as a "bad" conversion, to allow us
4894 // to exit early.
4895 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004896
4897 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004898 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004899 FromType = PT->getPointeeType();
4900
Douglas Gregor02824322011-01-26 19:30:28 +00004901 // When we had a pointer, it's implicitly dereferenced, so we
4902 // better have an lvalue.
4903 assert(FromClassification.isLValue());
4904 }
4905
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004906 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004907
Douglas Gregor02824322011-01-26 19:30:28 +00004908 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004909 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004910 // parameter is
4911 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004912 // - "lvalue reference to cv X" for functions declared without a
4913 // ref-qualifier or with the & ref-qualifier
4914 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004915 // ref-qualifier
4916 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004917 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004918 // cv-qualification on the member function declaration.
4919 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004920 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004921 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004922 // (C++ [over.match.funcs]p5). We perform a simplified version of
4923 // reference binding here, that allows class rvalues to bind to
4924 // non-constant references.
4925
Douglas Gregor02824322011-01-26 19:30:28 +00004926 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004927 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004928 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004929 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004930 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004931 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004932 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004933 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004934 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004935
4936 // Check that we have either the same type or a derived type. It
4937 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004938 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004939 ImplicitConversionKind SecondKind;
4940 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4941 SecondKind = ICK_Identity;
Richard Smith0f59cb32015-12-18 21:45:41 +00004942 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004943 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004944 else {
John McCall65eb8792010-02-25 01:37:24 +00004945 ICS.setBad(BadConversionSequence::unrelated_class,
4946 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004947 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004948 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004949
Douglas Gregor02824322011-01-26 19:30:28 +00004950 // Check the ref-qualifier.
4951 switch (Method->getRefQualifier()) {
4952 case RQ_None:
4953 // Do nothing; we don't care about lvalueness or rvalueness.
4954 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004955
Douglas Gregor02824322011-01-26 19:30:28 +00004956 case RQ_LValue:
4957 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4958 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004959 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004960 ImplicitParamType);
4961 return ICS;
4962 }
4963 break;
4964
4965 case RQ_RValue:
4966 if (!FromClassification.isRValue()) {
4967 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004968 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004969 ImplicitParamType);
4970 return ICS;
4971 }
4972 break;
4973 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004974
Douglas Gregor436424c2008-11-18 23:14:02 +00004975 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004976 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004977 ICS.Standard.setAsIdentityConversion();
4978 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004979 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004980 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004981 ICS.Standard.ReferenceBinding = true;
4982 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004983 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004984 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004985 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4986 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4987 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004988 return ICS;
4989}
4990
4991/// PerformObjectArgumentInitialization - Perform initialization of
4992/// the implicit object parameter for the given Method with the given
4993/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004994ExprResult
4995Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004996 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004997 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004998 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004999 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00005000 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005001 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005002
Douglas Gregor02824322011-01-26 19:30:28 +00005003 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005004 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005005 FromRecordType = PT->getPointeeType();
5006 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00005007 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005008 } else {
5009 FromRecordType = From->getType();
5010 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00005011 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005012 }
5013
John McCall6e9f8f62009-12-03 04:06:58 +00005014 // Note that we always use the true parent context when performing
5015 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00005016 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
Richard Smith0f59cb32015-12-18 21:45:41 +00005017 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5018 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005019 if (ICS.isBad()) {
5020 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5021 Qualifiers FromQs = FromRecordType.getQualifiers();
5022 Qualifiers ToQs = DestType.getQualifiers();
5023 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5024 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005025 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005026 diag::err_member_function_call_bad_cvr)
5027 << Method->getDeclName() << FromRecordType << (CVR - 1)
5028 << From->getSourceRange();
5029 Diag(Method->getLocation(), diag::note_previous_decl)
5030 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00005031 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005032 }
5033 }
5034
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005035 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005036 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005037 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00005038 }
Mike Stump11289f42009-09-09 15:08:12 +00005039
John Wiegley01296292011-04-08 18:41:53 +00005040 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5041 ExprResult FromRes =
5042 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5043 if (FromRes.isInvalid())
5044 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005045 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00005046 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005047
Douglas Gregorcc3f3252010-03-03 23:55:11 +00005048 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00005049 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005050 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005051 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00005052}
5053
Douglas Gregor5fb53972009-01-14 15:45:31 +00005054/// TryContextuallyConvertToBool - Attempt to contextually convert the
5055/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00005056static ImplicitConversionSequence
5057TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00005058 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00005059 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00005060 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00005061 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00005062 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005063 /*AllowObjCWritebackConversion=*/false,
5064 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005065}
5066
5067/// PerformContextuallyConvertToBool - Perform a contextual conversion
5068/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00005069ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005070 if (checkPlaceholderForOverload(*this, From))
5071 return ExprError();
5072
John McCall5c32be02010-08-24 20:38:10 +00005073 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00005074 if (!ICS.isBad())
5075 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076
Fariborz Jahanian76197412009-11-18 18:26:29 +00005077 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005078 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00005079 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00005080 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005081 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00005082}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005083
Richard Smithf8379a02012-01-18 23:55:52 +00005084/// Check that the specified conversion is permitted in a converted constant
5085/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5086/// is acceptable.
5087static bool CheckConvertedConstantConversions(Sema &S,
5088 StandardConversionSequence &SCS) {
5089 // Since we know that the target type is an integral or unscoped enumeration
5090 // type, most conversion kinds are impossible. All possible First and Third
5091 // conversions are fine.
5092 switch (SCS.Second) {
5093 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00005094 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00005095 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00005096 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00005097 return true;
5098
5099 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00005100 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00005101 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5102 // conversion, so we allow it in a converted constant expression.
5103 //
5104 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5105 // a lot of popular code. We should at least add a warning for this
5106 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00005107 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5108 SCS.getToType(2)->isBooleanType();
5109
Richard Smith410cc892014-11-26 03:26:53 +00005110 case ICK_Pointer_Conversion:
5111 case ICK_Pointer_Member:
5112 // C++1z: null pointer conversions and null member pointer conversions are
5113 // only permitted if the source type is std::nullptr_t.
5114 return SCS.getFromType()->isNullPtrType();
5115
5116 case ICK_Floating_Promotion:
5117 case ICK_Complex_Promotion:
5118 case ICK_Floating_Conversion:
5119 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005120 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00005121 case ICK_Compatible_Conversion:
5122 case ICK_Derived_To_Base:
5123 case ICK_Vector_Conversion:
5124 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00005125 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00005126 case ICK_Block_Pointer_Conversion:
5127 case ICK_TransparentUnionConversion:
5128 case ICK_Writeback_Conversion:
5129 case ICK_Zero_Event_Conversion:
George Burgess IV45461812015-10-11 20:13:20 +00005130 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00005131 case ICK_Incompatible_Pointer_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005132 return false;
5133
5134 case ICK_Lvalue_To_Rvalue:
5135 case ICK_Array_To_Pointer:
5136 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00005137 llvm_unreachable("found a first conversion kind in Second");
5138
Richard Smithf8379a02012-01-18 23:55:52 +00005139 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00005140 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00005141
5142 case ICK_Num_Conversion_Kinds:
5143 break;
5144 }
5145
5146 llvm_unreachable("unknown conversion kind");
5147}
5148
5149/// CheckConvertedConstantExpression - Check that the expression From is a
5150/// converted constant expression of type T, perform the conversion and produce
5151/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005152static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5153 QualType T, APValue &Value,
5154 Sema::CCEKind CCE,
5155 bool RequireInt) {
5156 assert(S.getLangOpts().CPlusPlus11 &&
5157 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005158
Richard Smith410cc892014-11-26 03:26:53 +00005159 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005160 return ExprError();
5161
Richard Smith410cc892014-11-26 03:26:53 +00005162 // C++1z [expr.const]p3:
5163 // A converted constant expression of type T is an expression,
5164 // implicitly converted to type T, where the converted
5165 // expression is a constant expression and the implicit conversion
5166 // sequence contains only [... list of conversions ...].
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005167 // C++1z [stmt.if]p2:
5168 // If the if statement is of the form if constexpr, the value of the
5169 // condition shall be a contextually converted constant expression of type
5170 // bool.
Richard Smithf8379a02012-01-18 23:55:52 +00005171 ImplicitConversionSequence ICS =
Ismail Pazarbasi4a007742016-09-07 18:24:54 +00005172 CCE == Sema::CCEK_ConstexprIf
5173 ? TryContextuallyConvertToBool(S, From)
5174 : TryCopyInitialization(S, From, T,
5175 /*SuppressUserConversions=*/false,
5176 /*InOverloadResolution=*/false,
5177 /*AllowObjcWritebackConversion=*/false,
5178 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005179 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005180 switch (ICS.getKind()) {
5181 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005182 SCS = &ICS.Standard;
5183 break;
5184 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005185 // We are converting to a non-class type, so the Before sequence
5186 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005187 SCS = &ICS.UserDefined.After;
5188 break;
5189 case ImplicitConversionSequence::AmbiguousConversion:
5190 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005191 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5192 return S.Diag(From->getLocStart(),
5193 diag::err_typecheck_converted_constant_expression)
5194 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005195 return ExprError();
5196
5197 case ImplicitConversionSequence::EllipsisConversion:
5198 llvm_unreachable("ellipsis conversion in converted constant expression");
5199 }
5200
Richard Smith410cc892014-11-26 03:26:53 +00005201 // Check that we would only use permitted conversions.
5202 if (!CheckConvertedConstantConversions(S, *SCS)) {
5203 return S.Diag(From->getLocStart(),
5204 diag::err_typecheck_converted_constant_expression_disallowed)
5205 << From->getType() << From->getSourceRange() << T;
5206 }
5207 // [...] and where the reference binding (if any) binds directly.
5208 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5209 return S.Diag(From->getLocStart(),
5210 diag::err_typecheck_converted_constant_expression_indirect)
5211 << From->getType() << From->getSourceRange() << T;
5212 }
5213
5214 ExprResult Result =
5215 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005216 if (Result.isInvalid())
5217 return Result;
5218
5219 // Check for a narrowing implicit conversion.
5220 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005221 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005222 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005223 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005224 case NK_Variable_Narrowing:
5225 // Implicit conversion to a narrower type, and the value is not a constant
5226 // expression. We'll diagnose this in a moment.
5227 case NK_Not_Narrowing:
5228 break;
5229
5230 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005231 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005232 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005233 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005234 break;
5235
5236 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005237 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005238 << CCE << /*Constant*/0 << From->getType() << T;
5239 break;
5240 }
5241
5242 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005243 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005244 Expr::EvalResult Eval;
5245 Eval.Diag = &Notes;
5246
Richard Smith410cc892014-11-26 03:26:53 +00005247 if ((T->isReferenceType()
5248 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5249 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5250 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005251 // The expression can't be folded, so we can't keep it at this position in
5252 // the AST.
5253 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005254 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005255 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005256
5257 if (Notes.empty()) {
5258 // It's a constant expression.
5259 return Result;
5260 }
Richard Smithf8379a02012-01-18 23:55:52 +00005261 }
5262
5263 // It's not a constant expression. Produce an appropriate diagnostic.
5264 if (Notes.size() == 1 &&
5265 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005266 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005267 else {
Richard Smith410cc892014-11-26 03:26:53 +00005268 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005269 << CCE << From->getSourceRange();
5270 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005271 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005272 }
Richard Smith410cc892014-11-26 03:26:53 +00005273 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005274}
5275
Richard Smith410cc892014-11-26 03:26:53 +00005276ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5277 APValue &Value, CCEKind CCE) {
5278 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5279}
5280
5281ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5282 llvm::APSInt &Value,
5283 CCEKind CCE) {
5284 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5285
5286 APValue V;
5287 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5288 if (!R.isInvalid())
5289 Value = V.getInt();
5290 return R;
5291}
5292
5293
John McCallfec112d2011-09-09 06:11:02 +00005294/// dropPointerConversions - If the given standard conversion sequence
5295/// involves any pointer conversions, remove them. This may change
5296/// the result type of the conversion sequence.
5297static void dropPointerConversion(StandardConversionSequence &SCS) {
5298 if (SCS.Second == ICK_Pointer_Conversion) {
5299 SCS.Second = ICK_Identity;
5300 SCS.Third = ICK_Identity;
5301 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5302 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005303}
John McCall5c32be02010-08-24 20:38:10 +00005304
John McCallfec112d2011-09-09 06:11:02 +00005305/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5306/// convert the expression From to an Objective-C pointer type.
5307static ImplicitConversionSequence
5308TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5309 // Do an implicit conversion to 'id'.
5310 QualType Ty = S.Context.getObjCIdType();
5311 ImplicitConversionSequence ICS
5312 = TryImplicitConversion(S, From, Ty,
5313 // FIXME: Are these flags correct?
5314 /*SuppressUserConversions=*/false,
5315 /*AllowExplicit=*/true,
5316 /*InOverloadResolution=*/false,
5317 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005318 /*AllowObjCWritebackConversion=*/false,
5319 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005320
5321 // Strip off any final conversions to 'id'.
5322 switch (ICS.getKind()) {
5323 case ImplicitConversionSequence::BadConversion:
5324 case ImplicitConversionSequence::AmbiguousConversion:
5325 case ImplicitConversionSequence::EllipsisConversion:
5326 break;
5327
5328 case ImplicitConversionSequence::UserDefinedConversion:
5329 dropPointerConversion(ICS.UserDefined.After);
5330 break;
5331
5332 case ImplicitConversionSequence::StandardConversion:
5333 dropPointerConversion(ICS.Standard);
5334 break;
5335 }
5336
5337 return ICS;
5338}
5339
5340/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5341/// conversion of the expression From to an Objective-C pointer type.
5342ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005343 if (checkPlaceholderForOverload(*this, From))
5344 return ExprError();
5345
John McCall8b07ec22010-05-15 11:32:37 +00005346 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005347 ImplicitConversionSequence ICS =
5348 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005349 if (!ICS.isBad())
5350 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005351 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005352}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005353
Richard Smith8dd34252012-02-04 07:07:42 +00005354/// Determine whether the provided type is an integral type, or an enumeration
5355/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005356bool Sema::ICEConvertDiagnoser::match(QualType T) {
5357 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5358 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005359}
5360
Larisse Voufo236bec22013-06-10 06:50:24 +00005361static ExprResult
5362diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5363 Sema::ContextualImplicitConverter &Converter,
5364 QualType T, UnresolvedSetImpl &ViableConversions) {
5365
5366 if (Converter.Suppress)
5367 return ExprError();
5368
5369 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5370 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5371 CXXConversionDecl *Conv =
5372 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5373 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5374 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5375 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005376 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005377}
5378
5379static bool
5380diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5381 Sema::ContextualImplicitConverter &Converter,
5382 QualType T, bool HadMultipleCandidates,
5383 UnresolvedSetImpl &ExplicitConversions) {
5384 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5385 DeclAccessPair Found = ExplicitConversions[0];
5386 CXXConversionDecl *Conversion =
5387 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5388
5389 // The user probably meant to invoke the given explicit
5390 // conversion; use it.
5391 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5392 std::string TypeStr;
5393 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5394
5395 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5396 << FixItHint::CreateInsertion(From->getLocStart(),
5397 "static_cast<" + TypeStr + ">(")
5398 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005399 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005400 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5401
5402 // If we aren't in a SFINAE context, build a call to the
5403 // explicit conversion function.
5404 if (SemaRef.isSFINAEContext())
5405 return true;
5406
Craig Topperc3ec1492014-05-26 06:22:03 +00005407 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005408 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5409 HadMultipleCandidates);
5410 if (Result.isInvalid())
5411 return true;
5412 // Record usage of conversion in an implicit cast.
5413 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005414 CK_UserDefinedConversion, Result.get(),
5415 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005416 }
5417 return false;
5418}
5419
5420static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5421 Sema::ContextualImplicitConverter &Converter,
5422 QualType T, bool HadMultipleCandidates,
5423 DeclAccessPair &Found) {
5424 CXXConversionDecl *Conversion =
5425 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005426 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005427
5428 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5429 if (!Converter.SuppressConversion) {
5430 if (SemaRef.isSFINAEContext())
5431 return true;
5432
5433 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5434 << From->getSourceRange();
5435 }
5436
5437 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5438 HadMultipleCandidates);
5439 if (Result.isInvalid())
5440 return true;
5441 // Record usage of conversion in an implicit cast.
5442 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005443 CK_UserDefinedConversion, Result.get(),
5444 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005445 return false;
5446}
5447
5448static ExprResult finishContextualImplicitConversion(
5449 Sema &SemaRef, SourceLocation Loc, Expr *From,
5450 Sema::ContextualImplicitConverter &Converter) {
5451 if (!Converter.match(From->getType()) && !Converter.Suppress)
5452 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5453 << From->getSourceRange();
5454
5455 return SemaRef.DefaultLvalueConversion(From);
5456}
5457
5458static void
5459collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5460 UnresolvedSetImpl &ViableConversions,
5461 OverloadCandidateSet &CandidateSet) {
5462 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5463 DeclAccessPair FoundDecl = ViableConversions[I];
5464 NamedDecl *D = FoundDecl.getDecl();
5465 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5466 if (isa<UsingShadowDecl>(D))
5467 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5468
5469 CXXConversionDecl *Conv;
5470 FunctionTemplateDecl *ConvTemplate;
5471 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5472 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5473 else
5474 Conv = cast<CXXConversionDecl>(D);
5475
5476 if (ConvTemplate)
5477 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005478 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5479 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005480 else
5481 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005482 ToType, CandidateSet,
5483 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005484 }
5485}
5486
Richard Smithccc11812013-05-21 19:05:48 +00005487/// \brief Attempt to convert the given expression to a type which is accepted
5488/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005489///
Richard Smithccc11812013-05-21 19:05:48 +00005490/// This routine will attempt to convert an expression of class type to a
5491/// type accepted by the specified converter. In C++11 and before, the class
5492/// must have a single non-explicit conversion function converting to a matching
5493/// type. In C++1y, there can be multiple such conversion functions, but only
5494/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005495///
Douglas Gregor4799d032010-06-30 00:20:43 +00005496/// \param Loc The source location of the construct that requires the
5497/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005498///
James Dennett18348b62012-06-22 08:52:37 +00005499/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005500///
Richard Smithccc11812013-05-21 19:05:48 +00005501/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005502///
Douglas Gregor4799d032010-06-30 00:20:43 +00005503/// \returns The expression, converted to an integral or enumeration type if
5504/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005505ExprResult Sema::PerformContextualImplicitConversion(
5506 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005507 // We can't perform any more checking for type-dependent expressions.
5508 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005509 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005510
Eli Friedman1da70392012-01-26 00:26:18 +00005511 // Process placeholders immediately.
5512 if (From->hasPlaceholderType()) {
5513 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005514 if (result.isInvalid())
5515 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005516 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005517 }
5518
Richard Smithccc11812013-05-21 19:05:48 +00005519 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005520 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005521 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005522 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005523
5524 // FIXME: Check for missing '()' if T is a function type?
5525
Richard Smithccc11812013-05-21 19:05:48 +00005526 // We can only perform contextual implicit conversions on objects of class
5527 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005528 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005529 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005530 if (!Converter.Suppress)
5531 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005532 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005534
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005535 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005536 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005537 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005538 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005539
5540 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
Richard Smithdb0ac552015-12-18 22:40:25 +00005541 : Converter(Converter), From(From) {}
Richard Smithccc11812013-05-21 19:05:48 +00005542
Craig Toppere14c0f82014-03-12 04:55:44 +00005543 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005544 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005545 }
Richard Smithccc11812013-05-21 19:05:48 +00005546 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005547
Richard Smithdb0ac552015-12-18 22:40:25 +00005548 if (Converter.Suppress ? !isCompleteType(Loc, T)
5549 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005550 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005551
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005552 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005553 UnresolvedSet<4>
5554 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005555 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005556 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005557 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005558
Larisse Voufo236bec22013-06-10 06:50:24 +00005559 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005560 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005561
Larisse Voufo236bec22013-06-10 06:50:24 +00005562 // To check that there is only one target type, in C++1y:
5563 QualType ToType;
5564 bool HasUniqueTargetType = true;
5565
5566 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005567 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005568 NamedDecl *D = (*I)->getUnderlyingDecl();
5569 CXXConversionDecl *Conversion;
5570 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5571 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005572 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005573 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5574 else
5575 continue; // C++11 does not consider conversion operator templates(?).
5576 } else
5577 Conversion = cast<CXXConversionDecl>(D);
5578
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005579 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005580 "Conversion operator templates are considered potentially "
5581 "viable in C++1y");
5582
5583 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5584 if (Converter.match(CurToType) || ConvTemplate) {
5585
5586 if (Conversion->isExplicit()) {
5587 // FIXME: For C++1y, do we need this restriction?
5588 // cf. diagnoseNoViableConversion()
5589 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005590 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005591 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005592 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005593 if (ToType.isNull())
5594 ToType = CurToType.getUnqualifiedType();
5595 else if (HasUniqueTargetType &&
5596 (CurToType.getUnqualifiedType() != ToType))
5597 HasUniqueTargetType = false;
5598 }
5599 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005600 }
Richard Smith8dd34252012-02-04 07:07:42 +00005601 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005603
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005604 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005605 // C++1y [conv]p6:
5606 // ... An expression e of class type E appearing in such a context
5607 // is said to be contextually implicitly converted to a specified
5608 // type T and is well-formed if and only if e can be implicitly
5609 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005610 // for conversion functions whose return type is cv T or reference to
5611 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005612 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005613
Larisse Voufo236bec22013-06-10 06:50:24 +00005614 // If no unique T is found:
5615 if (ToType.isNull()) {
5616 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5617 HadMultipleCandidates,
5618 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005619 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005620 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005621 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005622
Larisse Voufo236bec22013-06-10 06:50:24 +00005623 // If more than one unique Ts are found:
5624 if (!HasUniqueTargetType)
5625 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5626 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005627
Larisse Voufo236bec22013-06-10 06:50:24 +00005628 // If one unique T is found:
5629 // First, build a candidate set from the previously recorded
5630 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005631 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005632 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5633 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005634
Larisse Voufo236bec22013-06-10 06:50:24 +00005635 // Then, perform overload resolution over the candidate set.
5636 OverloadCandidateSet::iterator Best;
5637 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5638 case OR_Success: {
5639 // Apply this conversion.
5640 DeclAccessPair Found =
5641 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5642 if (recordConversion(*this, Loc, From, Converter, T,
5643 HadMultipleCandidates, Found))
5644 return ExprError();
5645 break;
5646 }
5647 case OR_Ambiguous:
5648 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5649 ViableConversions);
5650 case OR_No_Viable_Function:
5651 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5652 HadMultipleCandidates,
5653 ExplicitConversions))
5654 return ExprError();
5655 // fall through 'OR_Deleted' case.
5656 case OR_Deleted:
5657 // We'll complain below about a non-integral condition type.
5658 break;
5659 }
5660 } else {
5661 switch (ViableConversions.size()) {
5662 case 0: {
5663 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5664 HadMultipleCandidates,
5665 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005666 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005667
Larisse Voufo236bec22013-06-10 06:50:24 +00005668 // We'll complain below about a non-integral condition type.
5669 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005670 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005671 case 1: {
5672 // Apply this conversion.
5673 DeclAccessPair Found = ViableConversions[0];
5674 if (recordConversion(*this, Loc, From, Converter, T,
5675 HadMultipleCandidates, Found))
5676 return ExprError();
5677 break;
5678 }
5679 default:
5680 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5681 ViableConversions);
5682 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005683 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005684
Larisse Voufo236bec22013-06-10 06:50:24 +00005685 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005686}
5687
Richard Smith100b24a2014-04-17 01:52:14 +00005688/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5689/// an acceptable non-member overloaded operator for a call whose
5690/// arguments have types T1 (and, if non-empty, T2). This routine
5691/// implements the check in C++ [over.match.oper]p3b2 concerning
5692/// enumeration types.
5693static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5694 FunctionDecl *Fn,
5695 ArrayRef<Expr *> Args) {
5696 QualType T1 = Args[0]->getType();
5697 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5698
5699 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5700 return true;
5701
5702 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5703 return true;
5704
5705 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5706 if (Proto->getNumParams() < 1)
5707 return false;
5708
5709 if (T1->isEnumeralType()) {
5710 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5711 if (Context.hasSameUnqualifiedType(T1, ArgType))
5712 return true;
5713 }
5714
5715 if (Proto->getNumParams() < 2)
5716 return false;
5717
5718 if (!T2.isNull() && T2->isEnumeralType()) {
5719 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5720 if (Context.hasSameUnqualifiedType(T2, ArgType))
5721 return true;
5722 }
5723
5724 return false;
5725}
5726
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005727/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005728/// candidate functions, using the given function call arguments. If
5729/// @p SuppressUserConversions, then don't allow user-defined
5730/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005731///
James Dennett2a4d13c2012-06-15 07:13:21 +00005732/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005733/// based on an incomplete set of function arguments. This feature is used by
5734/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005735void
5736Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005737 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005738 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005739 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005740 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005741 bool PartialOverloading,
5742 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005743 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005744 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005745 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005746 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005747 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005748
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005749 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005750 if (!isa<CXXConstructorDecl>(Method)) {
5751 // If we get here, it's because we're calling a member function
5752 // that is named without a member access expression (e.g.,
5753 // "this->f") that was either written explicitly or created
5754 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005755 // function, e.g., X::f(). We use an empty type for the implied
5756 // object argument (C++ [over.call.func]p3), and the acting context
5757 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005758 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005759 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005760 Args, CandidateSet, SuppressUserConversions,
5761 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005762 return;
5763 }
5764 // We treat a constructor like a non-member function, since its object
5765 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005766 }
5767
Douglas Gregorff7028a2009-11-13 23:59:09 +00005768 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005769 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005770
Richard Smith100b24a2014-04-17 01:52:14 +00005771 // C++ [over.match.oper]p3:
5772 // if no operand has a class type, only those non-member functions in the
5773 // lookup set that have a first parameter of type T1 or "reference to
5774 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5775 // is a right operand) a second parameter of type T2 or "reference to
5776 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5777 // candidate functions.
5778 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5779 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5780 return;
5781
Richard Smith8b86f2d2013-11-04 01:48:18 +00005782 // C++11 [class.copy]p11: [DR1402]
5783 // A defaulted move constructor that is defined as deleted is ignored by
5784 // overload resolution.
5785 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5786 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5787 Constructor->isMoveConstructor())
5788 return;
5789
Douglas Gregor27381f32009-11-23 12:27:39 +00005790 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005791 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005792
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005793 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005794 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005795 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005796 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005797 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005798 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005799 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005800 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005801
John McCall578a1f82014-12-14 01:46:53 +00005802 if (Constructor) {
5803 // C++ [class.copy]p3:
5804 // A member function template is never instantiated to perform the copy
5805 // of a class object to an object of its class type.
5806 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Richard Smith0f59cb32015-12-18 21:45:41 +00005807 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
John McCall578a1f82014-12-14 01:46:53 +00005808 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
Richard Smith0f59cb32015-12-18 21:45:41 +00005809 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5810 ClassType))) {
John McCall578a1f82014-12-14 01:46:53 +00005811 Candidate.Viable = false;
5812 Candidate.FailureKind = ovl_fail_illegal_constructor;
5813 return;
5814 }
5815 }
5816
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005817 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005818
5819 // (C++ 13.3.2p2): A candidate function having fewer than m
5820 // parameters is viable only if it has an ellipsis in its parameter
5821 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005822 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005823 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005824 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005825 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005826 return;
5827 }
5828
5829 // (C++ 13.3.2p2): A candidate function having more than m parameters
5830 // is viable only if the (m+1)st parameter has a default argument
5831 // (8.3.6). For the purposes of overload resolution, the
5832 // parameter list is truncated on the right, so that there are
5833 // exactly m parameters.
5834 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005835 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005836 // Not enough arguments.
5837 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005838 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005839 return;
5840 }
5841
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005842 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005843 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005844 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005845 // Skip the check for callers that are implicit members, because in this
5846 // case we may not yet know what the member's target is; the target is
5847 // inferred for the member automatically, based on the bases and fields of
5848 // the class.
Justin Lebarb0080032016-08-10 01:09:11 +00005849 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005850 Candidate.Viable = false;
5851 Candidate.FailureKind = ovl_fail_bad_target;
5852 return;
5853 }
5854
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005855 // Determine the implicit conversion sequences for each of the
5856 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005857 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005858 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005859 // (C++ 13.3.2p3): for F to be a viable function, there shall
5860 // exist for each argument an implicit conversion sequence
5861 // (13.3.3.1) that converts that argument to the corresponding
5862 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005863 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005864 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005865 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005866 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005867 /*InOverloadResolution=*/true,
5868 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005869 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005870 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005871 if (Candidate.Conversions[ArgIdx].isBad()) {
5872 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005873 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005874 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005875 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005876 } else {
5877 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5878 // argument for which there is no corresponding parameter is
5879 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005880 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005881 }
5882 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005883
5884 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5885 Candidate.Viable = false;
5886 Candidate.FailureKind = ovl_fail_enable_if;
5887 Candidate.DeductionFailure.Data = FailedAttr;
5888 return;
5889 }
5890}
5891
Manman Rend2a3cd72016-04-07 19:30:20 +00005892ObjCMethodDecl *
5893Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5894 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5895 if (Methods.size() <= 1)
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005896 return nullptr;
Manman Rend2a3cd72016-04-07 19:30:20 +00005897
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005898 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5899 bool Match = true;
5900 ObjCMethodDecl *Method = Methods[b];
5901 unsigned NumNamedArgs = Sel.getNumArgs();
5902 // Method might have more arguments than selector indicates. This is due
5903 // to addition of c-style arguments in method.
5904 if (Method->param_size() > NumNamedArgs)
5905 NumNamedArgs = Method->param_size();
5906 if (Args.size() < NumNamedArgs)
5907 continue;
5908
5909 for (unsigned i = 0; i < NumNamedArgs; i++) {
5910 // We can't do any type-checking on a type-dependent argument.
5911 if (Args[i]->isTypeDependent()) {
5912 Match = false;
5913 break;
5914 }
5915
5916 ParmVarDecl *param = Method->parameters()[i];
5917 Expr *argExpr = Args[i];
5918 assert(argExpr && "SelectBestMethod(): missing expression");
5919
5920 // Strip the unbridged-cast placeholder expression off unless it's
5921 // a consumed argument.
5922 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5923 !param->hasAttr<CFConsumedAttr>())
5924 argExpr = stripARCUnbridgedCast(argExpr);
5925
5926 // If the parameter is __unknown_anytype, move on to the next method.
5927 if (param->getType() == Context.UnknownAnyTy) {
5928 Match = false;
5929 break;
5930 }
George Burgess IV45461812015-10-11 20:13:20 +00005931
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005932 ImplicitConversionSequence ConversionState
5933 = TryCopyInitialization(*this, argExpr, param->getType(),
5934 /*SuppressUserConversions*/false,
5935 /*InOverloadResolution=*/true,
5936 /*AllowObjCWritebackConversion=*/
5937 getLangOpts().ObjCAutoRefCount,
5938 /*AllowExplicit*/false);
George Burgess IV2099b542016-09-02 22:59:57 +00005939 // This function looks for a reasonably-exact match, so we consider
5940 // incompatible pointer conversions to be a failure here.
5941 if (ConversionState.isBad() ||
5942 (ConversionState.isStandard() &&
5943 ConversionState.Standard.Second ==
5944 ICK_Incompatible_Pointer_Conversion)) {
5945 Match = false;
5946 break;
5947 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005948 }
5949 // Promote additional arguments to variadic methods.
5950 if (Match && Method->isVariadic()) {
5951 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5952 if (Args[i]->isTypeDependent()) {
5953 Match = false;
5954 break;
5955 }
5956 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5957 nullptr);
5958 if (Arg.isInvalid()) {
5959 Match = false;
5960 break;
5961 }
5962 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005963 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005964 // Check for extra arguments to non-variadic methods.
5965 if (Args.size() != NumNamedArgs)
5966 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005967 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5968 // Special case when selectors have no argument. In this case, select
5969 // one with the most general result type of 'id'.
5970 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5971 QualType ReturnT = Methods[b]->getReturnType();
5972 if (ReturnT->isObjCIdType())
5973 return Methods[b];
5974 }
5975 }
5976 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005977
5978 if (Match)
5979 return Method;
5980 }
5981 return nullptr;
5982}
5983
George Burgess IV2a6150d2015-10-16 01:17:38 +00005984// specific_attr_iterator iterates over enable_if attributes in reverse, and
5985// enable_if is order-sensitive. As a result, we need to reverse things
5986// sometimes. Size of 4 elements is arbitrary.
5987static SmallVector<EnableIfAttr *, 4>
5988getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5989 SmallVector<EnableIfAttr *, 4> Result;
5990 if (!Function->hasAttrs())
5991 return Result;
5992
5993 const auto &FuncAttrs = Function->getAttrs();
5994 for (Attr *Attr : FuncAttrs)
5995 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5996 Result.push_back(EnableIf);
5997
5998 std::reverse(Result.begin(), Result.end());
5999 return Result;
6000}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006001
6002EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6003 bool MissingImplicitThis) {
George Burgess IV2a6150d2015-10-16 01:17:38 +00006004 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6005 if (EnableIfAttrs.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00006006 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006007
6008 SFINAETrap Trap(*this);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006009 SmallVector<Expr *, 16> ConvertedArgs;
6010 bool InitializationFailed = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00006011
George Burgess IV458b3f32016-08-12 04:19:35 +00006012 // Ignore any variadic arguments. Converting them is pointless, since the
George Burgess IV53b938d2016-08-12 04:12:31 +00006013 // user can't refer to them in the enable_if condition.
6014 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6015
Nick Lewyckye283c552015-08-25 22:33:16 +00006016 // Convert the arguments.
George Burgess IV53b938d2016-08-12 04:12:31 +00006017 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
George Burgess IVe96abf72016-02-24 22:31:14 +00006018 ExprResult R;
6019 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00006020 !cast<CXXMethodDecl>(Function)->isStatic() &&
6021 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006022 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
George Burgess IVe96abf72016-02-24 22:31:14 +00006023 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6024 Method, Method);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006025 } else {
George Burgess IVe96abf72016-02-24 22:31:14 +00006026 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6027 Context, Function->getParamDecl(I)),
6028 SourceLocation(), Args[I]);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006029 }
George Burgess IVe96abf72016-02-24 22:31:14 +00006030
6031 if (R.isInvalid()) {
6032 InitializationFailed = true;
6033 break;
6034 }
6035
George Burgess IVe96abf72016-02-24 22:31:14 +00006036 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006037 }
6038
6039 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006040 return EnableIfAttrs[0];
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006041
Nick Lewyckye283c552015-08-25 22:33:16 +00006042 // Push default arguments if needed.
6043 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6044 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6045 ParmVarDecl *P = Function->getParamDecl(i);
6046 ExprResult R = PerformCopyInitialization(
6047 InitializedEntity::InitializeParameter(Context,
6048 Function->getParamDecl(i)),
6049 SourceLocation(),
6050 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6051 : P->getDefaultArg());
6052 if (R.isInvalid()) {
6053 InitializationFailed = true;
6054 break;
6055 }
Nick Lewyckye283c552015-08-25 22:33:16 +00006056 ConvertedArgs.push_back(R.get());
6057 }
6058
6059 if (InitializationFailed || Trap.hasErrorOccurred())
George Burgess IV2a6150d2015-10-16 01:17:38 +00006060 return EnableIfAttrs[0];
Nick Lewyckye283c552015-08-25 22:33:16 +00006061 }
6062
George Burgess IV2a6150d2015-10-16 01:17:38 +00006063 for (auto *EIA : EnableIfAttrs) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006064 APValue Result;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006065 // FIXME: This doesn't consider value-dependent cases, because doing so is
6066 // very difficult. Ideally, we should handle them more gracefully.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006067 if (!EIA->getCond()->EvaluateWithSubstitution(
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006068 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006069 return EIA;
George Burgess IVe8f10cc2016-05-11 01:38:27 +00006070
6071 if (!Result.isInt() || !Result.getInt().getBoolValue())
6072 return EIA;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006073 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006074 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006075}
6076
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006077/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00006078/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00006079void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006080 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006081 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006082 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00006083 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006084 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00006085 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00006086 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6087 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006088 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006089 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006090 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00006091 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006092 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006093 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006094 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006095 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006096 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006097 } else {
John McCalla0296f72010-03-19 07:35:19 +00006098 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006099 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6100 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00006101 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00006102 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006103 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006104 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006105 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006106 CandidateSet, SuppressUserConversions,
6107 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006108 else
John McCalla0296f72010-03-19 07:35:19 +00006109 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00006110 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006111 CandidateSet, SuppressUserConversions,
6112 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006113 }
Douglas Gregor15448f82009-06-27 21:05:07 +00006114 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006115}
6116
John McCallf0f1cf02009-11-17 07:50:12 +00006117/// AddMethodCandidate - Adds a named decl (which is some kind of
6118/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00006119void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006120 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006121 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006122 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00006123 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006124 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00006125 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00006126 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00006127
6128 if (isa<UsingShadowDecl>(Decl))
6129 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006130
John McCallf0f1cf02009-11-17 07:50:12 +00006131 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6132 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6133 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00006134 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00006135 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006136 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006137 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006138 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006139 } else {
John McCalla0296f72010-03-19 07:35:19 +00006140 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006141 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00006142 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00006143 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00006144 }
6145}
6146
Douglas Gregor436424c2008-11-18 23:14:02 +00006147/// AddMethodCandidate - Adds the given C++ member function to the set
6148/// of candidate functions, using the given function call arguments
6149/// and the object argument (@c Object). For example, in a call
6150/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6151/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6152/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00006153/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00006154void
John McCalla0296f72010-03-19 07:35:19 +00006155Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00006156 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006157 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006158 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006159 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006160 bool SuppressUserConversions,
6161 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006162 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00006163 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006164 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006165 assert(!isa<CXXConstructorDecl>(Method) &&
6166 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006167
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006168 if (!CandidateSet.isNewCandidate(Method))
6169 return;
6170
Richard Smith8b86f2d2013-11-04 01:48:18 +00006171 // C++11 [class.copy]p23: [DR1402]
6172 // A defaulted move assignment operator that is defined as deleted is
6173 // ignored by overload resolution.
6174 if (Method->isDefaulted() && Method->isDeleted() &&
6175 Method->isMoveAssignmentOperator())
6176 return;
6177
Douglas Gregor27381f32009-11-23 12:27:39 +00006178 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006179 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006180
Douglas Gregor436424c2008-11-18 23:14:02 +00006181 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006182 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006183 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006184 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006185 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006186 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006187 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006188
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006189 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006190
6191 // (C++ 13.3.2p2): A candidate function having fewer than m
6192 // parameters is viable only if it has an ellipsis in its parameter
6193 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006194 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6195 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006196 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006197 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006198 return;
6199 }
6200
6201 // (C++ 13.3.2p2): A candidate function having more than m parameters
6202 // is viable only if the (m+1)st parameter has a default argument
6203 // (8.3.6). For the purposes of overload resolution, the
6204 // parameter list is truncated on the right, so that there are
6205 // exactly m parameters.
6206 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006207 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006208 // Not enough arguments.
6209 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006210 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006211 return;
6212 }
6213
6214 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006215
John McCall6e9f8f62009-12-03 04:06:58 +00006216 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006217 // The implicit object argument is ignored.
6218 Candidate.IgnoreObjectArgument = true;
6219 else {
6220 // Determine the implicit conversion sequence for the object
6221 // parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006222 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6223 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6224 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006225 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006226 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006227 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006228 return;
6229 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006230 }
6231
Eli Bendersky291a57e2014-09-25 23:59:08 +00006232 // (CUDA B.1): Check for invalid calls between targets.
6233 if (getLangOpts().CUDA)
6234 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +00006235 if (!IsAllowedCUDACall(Caller, Method)) {
Eli Bendersky291a57e2014-09-25 23:59:08 +00006236 Candidate.Viable = false;
6237 Candidate.FailureKind = ovl_fail_bad_target;
6238 return;
6239 }
6240
Douglas Gregor436424c2008-11-18 23:14:02 +00006241 // Determine the implicit conversion sequences for each of the
6242 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006243 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006244 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006245 // (C++ 13.3.2p3): for F to be a viable function, there shall
6246 // exist for each argument an implicit conversion sequence
6247 // (13.3.3.1) that converts that argument to the corresponding
6248 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006249 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006250 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006251 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006252 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006253 /*InOverloadResolution=*/true,
6254 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006255 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006256 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006257 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006258 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006259 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006260 }
6261 } else {
6262 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6263 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006264 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006265 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006266 }
6267 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006268
6269 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6270 Candidate.Viable = false;
6271 Candidate.FailureKind = ovl_fail_enable_if;
6272 Candidate.DeductionFailure.Data = FailedAttr;
6273 return;
6274 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006275}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006276
Douglas Gregor97628d62009-08-21 00:16:32 +00006277/// \brief Add a C++ member function template as a candidate to the candidate
6278/// set, using template argument deduction to produce an appropriate member
6279/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006280void
Douglas Gregor97628d62009-08-21 00:16:32 +00006281Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006282 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006283 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006284 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006285 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006286 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006287 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006288 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006289 bool SuppressUserConversions,
6290 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006291 if (!CandidateSet.isNewCandidate(MethodTmpl))
6292 return;
6293
Douglas Gregor97628d62009-08-21 00:16:32 +00006294 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006295 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006296 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006297 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006298 // candidate functions in the usual way.113) A given name can refer to one
6299 // or more function templates and also to a set of overloaded non-template
6300 // functions. In such a case, the candidate functions generated from each
6301 // function template are combined with the set of non-template candidate
6302 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006303 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006304 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006305 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006306 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006307 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006308 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006309 Candidate.FoundDecl = FoundDecl;
6310 Candidate.Function = MethodTmpl->getTemplatedDecl();
6311 Candidate.Viable = false;
6312 Candidate.FailureKind = ovl_fail_bad_deduction;
6313 Candidate.IsSurrogate = false;
6314 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006315 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006316 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006317 Info);
6318 return;
6319 }
Mike Stump11289f42009-09-09 15:08:12 +00006320
Douglas Gregor97628d62009-08-21 00:16:32 +00006321 // Add the function template specialization produced by template argument
6322 // deduction as a candidate.
6323 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006324 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006325 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006326 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006327 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006328 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006329}
6330
Douglas Gregor05155d82009-08-21 23:19:43 +00006331/// \brief Add a C++ function template specialization as a candidate
6332/// in the candidate set, using template argument deduction to produce
6333/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006334void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006335Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006336 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006337 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006338 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006339 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006340 bool SuppressUserConversions,
6341 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006342 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6343 return;
6344
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006345 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006346 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006347 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006348 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006349 // candidate functions in the usual way.113) A given name can refer to one
6350 // or more function templates and also to a set of overloaded non-template
6351 // functions. In such a case, the candidate functions generated from each
6352 // function template are combined with the set of non-template candidate
6353 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006354 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006355 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006356 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006357 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006358 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006359 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006360 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006361 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6362 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006363 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006364 Candidate.IsSurrogate = false;
6365 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006366 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006367 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006368 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006369 return;
6370 }
Mike Stump11289f42009-09-09 15:08:12 +00006371
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006372 // Add the function template specialization produced by template argument
6373 // deduction as a candidate.
6374 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006375 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006376 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006377}
Mike Stump11289f42009-09-09 15:08:12 +00006378
Douglas Gregor4b60a152013-11-07 22:34:54 +00006379/// Determine whether this is an allowable conversion from the result
6380/// of an explicit conversion operator to the expected type, per C++
6381/// [over.match.conv]p1 and [over.match.ref]p1.
6382///
6383/// \param ConvType The return type of the conversion function.
6384///
6385/// \param ToType The type we are converting to.
6386///
6387/// \param AllowObjCPointerConversion Allow a conversion from one
6388/// Objective-C pointer to another.
6389///
6390/// \returns true if the conversion is allowable, false otherwise.
6391static bool isAllowableExplicitConversion(Sema &S,
6392 QualType ConvType, QualType ToType,
6393 bool AllowObjCPointerConversion) {
6394 QualType ToNonRefType = ToType.getNonReferenceType();
6395
6396 // Easy case: the types are the same.
6397 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6398 return true;
6399
6400 // Allow qualification conversions.
6401 bool ObjCLifetimeConversion;
6402 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6403 ObjCLifetimeConversion))
6404 return true;
6405
6406 // If we're not allowed to consider Objective-C pointer conversions,
6407 // we're done.
6408 if (!AllowObjCPointerConversion)
6409 return false;
6410
6411 // Is this an Objective-C pointer conversion?
6412 bool IncompatibleObjC = false;
6413 QualType ConvertedType;
6414 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6415 IncompatibleObjC);
6416}
6417
Douglas Gregora1f013e2008-11-07 22:36:19 +00006418/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006419/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006420/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006421/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006422/// (which may or may not be the same type as the type that the
6423/// conversion function produces).
6424void
6425Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006426 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006427 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006428 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006429 OverloadCandidateSet& CandidateSet,
6430 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006431 assert(!Conversion->getDescribedFunctionTemplate() &&
6432 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006433 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006434 if (!CandidateSet.isNewCandidate(Conversion))
6435 return;
6436
Richard Smith2a7d4812013-05-04 07:00:32 +00006437 // If the conversion function has an undeduced return type, trigger its
6438 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006439 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006440 if (DeduceReturnType(Conversion, From->getExprLoc()))
6441 return;
6442 ConvType = Conversion->getConversionType().getNonReferenceType();
6443 }
6444
Richard Smith089c3162013-09-21 21:55:46 +00006445 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6446 // operator is only a candidate if its return type is the target type or
6447 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006448 if (Conversion->isExplicit() &&
6449 !isAllowableExplicitConversion(*this, ConvType, ToType,
6450 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006451 return;
6452
Douglas Gregor27381f32009-11-23 12:27:39 +00006453 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006454 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006455
Douglas Gregora1f013e2008-11-07 22:36:19 +00006456 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006457 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006458 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006459 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006460 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006461 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006462 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006463 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006464 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006465 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006466 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006467
Douglas Gregor6affc782010-08-19 15:37:02 +00006468 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006469 // For conversion functions, the function is considered to be a member of
6470 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006471 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006472 //
6473 // Determine the implicit conversion sequence for the implicit
6474 // object parameter.
6475 QualType ImplicitParamType = From->getType();
6476 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6477 ImplicitParamType = FromPtrType->getPointeeType();
6478 CXXRecordDecl *ConversionContext
6479 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006480
Richard Smith0f59cb32015-12-18 21:45:41 +00006481 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6482 *this, CandidateSet.getLocation(), From->getType(),
6483 From->Classify(Context), Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006484
John McCall0d1da222010-01-12 00:44:57 +00006485 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006486 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006487 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006488 return;
6489 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006490
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006491 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006492 // derived to base as such conversions are given Conversion Rank. They only
6493 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6494 QualType FromCanon
6495 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6496 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00006497 if (FromCanon == ToCanon ||
6498 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006499 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006500 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006501 return;
6502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006503
Douglas Gregora1f013e2008-11-07 22:36:19 +00006504 // To determine what the conversion from the result of calling the
6505 // conversion function to the type we're eventually trying to
6506 // convert to (ToType), we need to synthesize a call to the
6507 // conversion function and attempt copy initialization from it. This
6508 // makes sure that we get the right semantics with respect to
6509 // lvalues/rvalues and the type. Fortunately, we can allocate this
6510 // call on the stack and we don't need its arguments to be
6511 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006512 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006513 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006514 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6515 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006516 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006517 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006518
Richard Smith48d24642011-07-13 22:53:21 +00006519 QualType ConversionType = Conversion->getConversionType();
Richard Smithdb0ac552015-12-18 22:40:25 +00006520 if (!isCompleteType(From->getLocStart(), ConversionType)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006521 Candidate.Viable = false;
6522 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6523 return;
6524 }
6525
Richard Smith48d24642011-07-13 22:53:21 +00006526 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006527
Mike Stump11289f42009-09-09 15:08:12 +00006528 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006529 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6530 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006531 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006532 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006533 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006534 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006535 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006536 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006537 /*InOverloadResolution=*/false,
6538 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006539
John McCall0d1da222010-01-12 00:44:57 +00006540 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006541 case ImplicitConversionSequence::StandardConversion:
6542 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006543
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006544 // C++ [over.ics.user]p3:
6545 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006546 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006547 // shall have exact match rank.
6548 if (Conversion->getPrimaryTemplate() &&
6549 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6550 Candidate.Viable = false;
6551 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006552 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006553 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006554
Douglas Gregorcba72b12011-01-21 05:18:22 +00006555 // C++0x [dcl.init.ref]p5:
6556 // In the second case, if the reference is an rvalue reference and
6557 // the second standard conversion sequence of the user-defined
6558 // conversion sequence includes an lvalue-to-rvalue conversion, the
6559 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006560 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006561 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6562 Candidate.Viable = false;
6563 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006564 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006565 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006566 break;
6567
6568 case ImplicitConversionSequence::BadConversion:
6569 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006570 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006571 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006572
6573 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006574 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006575 "Can only end up with a standard conversion sequence or failure");
6576 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006577
Craig Topper5fc8fc22014-08-27 06:28:36 +00006578 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006579 Candidate.Viable = false;
6580 Candidate.FailureKind = ovl_fail_enable_if;
6581 Candidate.DeductionFailure.Data = FailedAttr;
6582 return;
6583 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006584}
6585
Douglas Gregor05155d82009-08-21 23:19:43 +00006586/// \brief Adds a conversion function template specialization
6587/// candidate to the overload set, using template argument deduction
6588/// to deduce the template arguments of the conversion function
6589/// template from the type that we are converting to (C++
6590/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006591void
Douglas Gregor05155d82009-08-21 23:19:43 +00006592Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006593 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006594 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006595 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006596 OverloadCandidateSet &CandidateSet,
6597 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006598 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6599 "Only conversion function templates permitted here");
6600
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006601 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6602 return;
6603
Craig Toppere6706e42012-09-19 02:26:47 +00006604 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006605 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006606 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006607 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006608 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006609 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006610 Candidate.FoundDecl = FoundDecl;
6611 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6612 Candidate.Viable = false;
6613 Candidate.FailureKind = ovl_fail_bad_deduction;
6614 Candidate.IsSurrogate = false;
6615 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006616 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006617 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006618 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006619 return;
6620 }
Mike Stump11289f42009-09-09 15:08:12 +00006621
Douglas Gregor05155d82009-08-21 23:19:43 +00006622 // Add the conversion function template specialization produced by
6623 // template argument deduction as a candidate.
6624 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006625 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006626 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006627}
6628
Douglas Gregorab7897a2008-11-19 22:57:39 +00006629/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6630/// converts the given @c Object to a function pointer via the
6631/// conversion function @c Conversion, and then attempts to call it
6632/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6633/// the type of function that we'll eventually be calling.
6634void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006635 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006636 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006637 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006638 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006639 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006640 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006641 if (!CandidateSet.isNewCandidate(Conversion))
6642 return;
6643
Douglas Gregor27381f32009-11-23 12:27:39 +00006644 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006645 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006646
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006647 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006648 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006649 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006650 Candidate.Surrogate = Conversion;
6651 Candidate.Viable = true;
6652 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006653 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006654 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006655
6656 // Determine the implicit conversion sequence for the implicit
6657 // object parameter.
Richard Smith0f59cb32015-12-18 21:45:41 +00006658 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6659 *this, CandidateSet.getLocation(), Object->getType(),
6660 Object->Classify(Context), Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006661 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006662 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006663 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006664 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006665 return;
6666 }
6667
6668 // The first conversion is actually a user-defined conversion whose
6669 // first conversion is ObjectInit's standard conversion (which is
6670 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006671 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006672 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006673 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006674 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006675 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006676 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006677 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006678 = Candidate.Conversions[0].UserDefined.Before;
6679 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6680
Mike Stump11289f42009-09-09 15:08:12 +00006681 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006682 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006683
6684 // (C++ 13.3.2p2): A candidate function having fewer than m
6685 // parameters is viable only if it has an ellipsis in its parameter
6686 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006687 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006688 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006689 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006690 return;
6691 }
6692
6693 // Function types don't have any default arguments, so just check if
6694 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006695 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006696 // Not enough arguments.
6697 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006698 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006699 return;
6700 }
6701
6702 // Determine the implicit conversion sequences for each of the
6703 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006704 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006705 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006706 // (C++ 13.3.2p3): for F to be a viable function, there shall
6707 // exist for each argument an implicit conversion sequence
6708 // (13.3.3.1) that converts that argument to the corresponding
6709 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006710 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006711 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006712 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006713 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006714 /*InOverloadResolution=*/false,
6715 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006716 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006717 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006718 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006719 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006720 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006721 }
6722 } else {
6723 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6724 // argument for which there is no corresponding parameter is
6725 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006726 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006727 }
6728 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006729
Craig Topper5fc8fc22014-08-27 06:28:36 +00006730 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006731 Candidate.Viable = false;
6732 Candidate.FailureKind = ovl_fail_enable_if;
6733 Candidate.DeductionFailure.Data = FailedAttr;
6734 return;
6735 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006736}
6737
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006738/// \brief Add overload candidates for overloaded operators that are
6739/// member functions.
6740///
6741/// Add the overloaded operator candidates that are member functions
6742/// for the operator Op that was used in an operator expression such
6743/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6744/// CandidateSet will store the added overload candidates. (C++
6745/// [over.match.oper]).
6746void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6747 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006748 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006749 OverloadCandidateSet& CandidateSet,
6750 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006751 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6752
6753 // C++ [over.match.oper]p3:
6754 // For a unary operator @ with an operand of a type whose
6755 // cv-unqualified version is T1, and for a binary operator @ with
6756 // a left operand of a type whose cv-unqualified version is T1 and
6757 // a right operand of a type whose cv-unqualified version is T2,
6758 // three sets of candidate functions, designated member
6759 // candidates, non-member candidates and built-in candidates, are
6760 // constructed as follows:
6761 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006762
Richard Smith0feaf0c2013-04-20 12:41:22 +00006763 // -- If T1 is a complete class type or a class currently being
6764 // defined, the set of member candidates is the result of the
6765 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6766 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006767 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006768 // Complete the type if it can be completed.
Richard Smithdb0ac552015-12-18 22:40:25 +00006769 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
Richard Smith82b8d4e2015-12-18 22:19:11 +00006770 return;
Richard Smith0feaf0c2013-04-20 12:41:22 +00006771 // If the type is neither complete nor being defined, bail out now.
6772 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006773 return;
Mike Stump11289f42009-09-09 15:08:12 +00006774
John McCall27b18f82009-11-17 02:14:36 +00006775 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6776 LookupQualifiedName(Operators, T1Rec->getDecl());
6777 Operators.suppressDiagnostics();
6778
Mike Stump11289f42009-09-09 15:08:12 +00006779 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006780 OperEnd = Operators.end();
6781 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006782 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006783 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006784 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006785 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006786 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006787 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006788 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006789}
6790
Douglas Gregora11693b2008-11-12 17:17:38 +00006791/// AddBuiltinCandidate - Add a candidate for a built-in
6792/// operator. ResultTy and ParamTys are the result and parameter types
6793/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006794/// arguments being passed to the candidate. IsAssignmentOperator
6795/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006796/// operator. NumContextualBoolArguments is the number of arguments
6797/// (at the beginning of the argument list) that will be contextually
6798/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006799void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006800 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006801 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006802 bool IsAssignmentOperator,
6803 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006804 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006805 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006806
Douglas Gregora11693b2008-11-12 17:17:38 +00006807 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006808 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006809 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6810 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006811 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006812 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006813 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006814 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006815 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6816
6817 // Determine the implicit conversion sequences for each of the
6818 // arguments.
6819 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006820 Candidate.ExplicitCallArguments = Args.size();
6821 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006822 // C++ [over.match.oper]p4:
6823 // For the built-in assignment operators, conversions of the
6824 // left operand are restricted as follows:
6825 // -- no temporaries are introduced to hold the left operand, and
6826 // -- no user-defined conversions are applied to the left
6827 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006828 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006829 //
6830 // We block these conversions by turning off user-defined
6831 // conversions, since that is the only way that initialization of
6832 // a reference to a non-class type can occur from something that
6833 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006834 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006835 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006836 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006837 Candidate.Conversions[ArgIdx]
6838 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006839 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006840 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006841 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006842 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006843 /*InOverloadResolution=*/false,
6844 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006845 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006846 }
John McCall0d1da222010-01-12 00:44:57 +00006847 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006848 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006849 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006850 break;
6851 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006852 }
6853}
6854
Craig Toppercd7b0332013-07-01 06:29:40 +00006855namespace {
6856
Douglas Gregora11693b2008-11-12 17:17:38 +00006857/// BuiltinCandidateTypeSet - A set of types that will be used for the
6858/// candidate operator functions for built-in operators (C++
6859/// [over.built]). The types are separated into pointer types and
6860/// enumeration types.
6861class BuiltinCandidateTypeSet {
6862 /// TypeSet - A set of types.
Richard Smith95853072016-03-25 00:08:53 +00006863 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6864 llvm::SmallPtrSet<QualType, 8>> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006865
6866 /// PointerTypes - The set of pointer types that will be used in the
6867 /// built-in candidates.
6868 TypeSet PointerTypes;
6869
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006870 /// MemberPointerTypes - The set of member pointer types that will be
6871 /// used in the built-in candidates.
6872 TypeSet MemberPointerTypes;
6873
Douglas Gregora11693b2008-11-12 17:17:38 +00006874 /// EnumerationTypes - The set of enumeration types that will be
6875 /// used in the built-in candidates.
6876 TypeSet EnumerationTypes;
6877
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006878 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006879 /// candidates.
6880 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006881
6882 /// \brief A flag indicating non-record types are viable candidates
6883 bool HasNonRecordTypes;
6884
6885 /// \brief A flag indicating whether either arithmetic or enumeration types
6886 /// were present in the candidate set.
6887 bool HasArithmeticOrEnumeralTypes;
6888
Douglas Gregor80af3132011-05-21 23:15:46 +00006889 /// \brief A flag indicating whether the nullptr type was present in the
6890 /// candidate set.
6891 bool HasNullPtrType;
6892
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006893 /// Sema - The semantic analysis instance where we are building the
6894 /// candidate type set.
6895 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006896
Douglas Gregora11693b2008-11-12 17:17:38 +00006897 /// Context - The AST context in which we will build the type sets.
6898 ASTContext &Context;
6899
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006900 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6901 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006902 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006903
6904public:
6905 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006906 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006907
Mike Stump11289f42009-09-09 15:08:12 +00006908 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006909 : HasNonRecordTypes(false),
6910 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006911 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006912 SemaRef(SemaRef),
6913 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006914
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006915 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006916 SourceLocation Loc,
6917 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006918 bool AllowExplicitConversions,
6919 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006920
6921 /// pointer_begin - First pointer type found;
6922 iterator pointer_begin() { return PointerTypes.begin(); }
6923
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006924 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006925 iterator pointer_end() { return PointerTypes.end(); }
6926
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006927 /// member_pointer_begin - First member pointer type found;
6928 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6929
6930 /// member_pointer_end - Past the last member pointer type found;
6931 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6932
Douglas Gregora11693b2008-11-12 17:17:38 +00006933 /// enumeration_begin - First enumeration type found;
6934 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6935
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006936 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006937 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006938
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006939 iterator vector_begin() { return VectorTypes.begin(); }
6940 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006941
6942 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6943 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006944 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006945};
6946
Craig Toppercd7b0332013-07-01 06:29:40 +00006947} // end anonymous namespace
6948
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006949/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006950/// the set of pointer types along with any more-qualified variants of
6951/// that type. For example, if @p Ty is "int const *", this routine
6952/// will add "int const *", "int const volatile *", "int const
6953/// restrict *", and "int const volatile restrict *" to the set of
6954/// pointer types. Returns true if the add of @p Ty itself succeeded,
6955/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006956///
6957/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006958bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006959BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6960 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006961
Douglas Gregora11693b2008-11-12 17:17:38 +00006962 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00006963 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006964 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006965
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006966 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006967 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006968 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006969 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006970 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6971 PointeeTy = PTy->getPointeeType();
6972 buildObjCPtr = true;
6973 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006974 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006975 }
6976
Sebastian Redl4990a632009-11-18 20:39:26 +00006977 // Don't add qualified variants of arrays. For one, they're not allowed
6978 // (the qualifier would sink to the element type), and for another, the
6979 // only overload situation where it matters is subscript or pointer +- int,
6980 // and those shouldn't have qualifier variants anyway.
6981 if (PointeeTy->isArrayType())
6982 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006983
John McCall8ccfcb52009-09-24 19:53:00 +00006984 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006985 bool hasVolatile = VisibleQuals.hasVolatile();
6986 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006987
John McCall8ccfcb52009-09-24 19:53:00 +00006988 // Iterate through all strict supersets of BaseCVR.
6989 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6990 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006991 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006992 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006993
6994 // Skip over restrict if no restrict found anywhere in the types, or if
6995 // the type cannot be restrict-qualified.
6996 if ((CVR & Qualifiers::Restrict) &&
6997 (!hasRestrict ||
6998 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6999 continue;
7000
7001 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00007002 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007003
7004 // Build qualified pointer type.
7005 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007006 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00007007 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00007008 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00007009 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7010
7011 // Insert qualified pointer type.
7012 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00007013 }
7014
7015 return true;
7016}
7017
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007018/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7019/// to the set of pointer types along with any more-qualified variants of
7020/// that type. For example, if @p Ty is "int const *", this routine
7021/// will add "int const *", "int const volatile *", "int const
7022/// restrict *", and "int const volatile restrict *" to the set of
7023/// pointer types. Returns true if the add of @p Ty itself succeeded,
7024/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00007025///
7026/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007027bool
7028BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7029 QualType Ty) {
7030 // Insert this type.
Richard Smith95853072016-03-25 00:08:53 +00007031 if (!MemberPointerTypes.insert(Ty))
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007032 return false;
7033
John McCall8ccfcb52009-09-24 19:53:00 +00007034 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7035 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007036
John McCall8ccfcb52009-09-24 19:53:00 +00007037 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00007038 // Don't add qualified variants of arrays. For one, they're not allowed
7039 // (the qualifier would sink to the element type), and for another, the
7040 // only overload situation where it matters is subscript or pointer +- int,
7041 // and those shouldn't have qualifier variants anyway.
7042 if (PointeeTy->isArrayType())
7043 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00007044 const Type *ClassTy = PointerTy->getClass();
7045
7046 // Iterate through all strict supersets of the pointee type's CVR
7047 // qualifiers.
7048 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7049 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7050 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007051
John McCall8ccfcb52009-09-24 19:53:00 +00007052 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007053 MemberPointerTypes.insert(
7054 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007055 }
7056
7057 return true;
7058}
7059
Douglas Gregora11693b2008-11-12 17:17:38 +00007060/// AddTypesConvertedFrom - Add each of the types to which the type @p
7061/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007062/// primarily interested in pointer types and enumeration types. We also
7063/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00007064/// AllowUserConversions is true if we should look at the conversion
7065/// functions of a class type, and AllowExplicitConversions if we
7066/// should also include the explicit conversion functions of a class
7067/// type.
Mike Stump11289f42009-09-09 15:08:12 +00007068void
Douglas Gregor5fb53972009-01-14 15:45:31 +00007069BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007070 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00007071 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007072 bool AllowExplicitConversions,
7073 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007074 // Only deal with canonical types.
7075 Ty = Context.getCanonicalType(Ty);
7076
7077 // Look through reference types; they aren't part of the type of an
7078 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007079 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00007080 Ty = RefTy->getPointeeType();
7081
John McCall33ddac02011-01-19 10:06:00 +00007082 // If we're dealing with an array type, decay to the pointer.
7083 if (Ty->isArrayType())
7084 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7085
7086 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007087 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00007088
Chandler Carruth00a38332010-12-13 01:44:01 +00007089 // Flag if we ever add a non-record type.
7090 const RecordType *TyRec = Ty->getAs<RecordType>();
7091 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7092
Chandler Carruth00a38332010-12-13 01:44:01 +00007093 // Flag if we encounter an arithmetic type.
7094 HasArithmeticOrEnumeralTypes =
7095 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7096
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00007097 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7098 PointerTypes.insert(Ty);
7099 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007100 // Insert our type, and its more-qualified variants, into the set
7101 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007102 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00007103 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00007104 } else if (Ty->isMemberPointerType()) {
7105 // Member pointers are far easier, since the pointee can't be converted.
7106 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7107 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00007108 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007109 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00007110 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007111 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007112 // We treat vector types as arithmetic types in many contexts as an
7113 // extension.
7114 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007115 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00007116 } else if (Ty->isNullPtrType()) {
7117 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00007118 } else if (AllowUserConversions && TyRec) {
7119 // No conversion functions in incomplete types.
Richard Smithdb0ac552015-12-18 22:40:25 +00007120 if (!SemaRef.isCompleteType(Loc, Ty))
Chandler Carruth00a38332010-12-13 01:44:01 +00007121 return;
Mike Stump11289f42009-09-09 15:08:12 +00007122
Chandler Carruth00a38332010-12-13 01:44:01 +00007123 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007124 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007125 if (isa<UsingShadowDecl>(D))
7126 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00007127
Chandler Carruth00a38332010-12-13 01:44:01 +00007128 // Skip conversion function templates; they don't tell us anything
7129 // about which builtin types we can convert to.
7130 if (isa<FunctionTemplateDecl>(D))
7131 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007132
Chandler Carruth00a38332010-12-13 01:44:01 +00007133 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7134 if (AllowExplicitConversions || !Conv->isExplicit()) {
7135 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7136 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00007137 }
7138 }
7139 }
7140}
7141
Douglas Gregor84605ae2009-08-24 13:43:27 +00007142/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7143/// the volatile- and non-volatile-qualified assignment operators for the
7144/// given type to the candidate set.
7145static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7146 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00007147 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007148 OverloadCandidateSet &CandidateSet) {
7149 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00007150
Douglas Gregor84605ae2009-08-24 13:43:27 +00007151 // T& operator=(T&, T)
7152 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7153 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007154 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00007155 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00007156
Douglas Gregor84605ae2009-08-24 13:43:27 +00007157 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7158 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00007159 ParamTypes[0]
7160 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00007161 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00007162 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00007163 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00007164 }
7165}
Mike Stump11289f42009-09-09 15:08:12 +00007166
Sebastian Redl1054fae2009-10-25 17:03:50 +00007167/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7168/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007169static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7170 Qualifiers VRQuals;
7171 const RecordType *TyRec;
7172 if (const MemberPointerType *RHSMPType =
7173 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007174 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007175 else
7176 TyRec = ArgExpr->getType()->getAs<RecordType>();
7177 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007178 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007179 VRQuals.addVolatile();
7180 VRQuals.addRestrict();
7181 return VRQuals;
7182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007183
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007184 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007185 if (!ClassDecl->hasDefinition())
7186 return VRQuals;
7187
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007188 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007189 if (isa<UsingShadowDecl>(D))
7190 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7191 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007192 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7193 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7194 CanTy = ResTypeRef->getPointeeType();
7195 // Need to go down the pointer/mempointer chain and add qualifiers
7196 // as see them.
7197 bool done = false;
7198 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007199 if (CanTy.isRestrictQualified())
7200 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007201 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7202 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007203 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007204 CanTy->getAs<MemberPointerType>())
7205 CanTy = ResTypeMPtr->getPointeeType();
7206 else
7207 done = true;
7208 if (CanTy.isVolatileQualified())
7209 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007210 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7211 return VRQuals;
7212 }
7213 }
7214 }
7215 return VRQuals;
7216}
John McCall52872982010-11-13 05:51:15 +00007217
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007218namespace {
John McCall52872982010-11-13 05:51:15 +00007219
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007220/// \brief Helper class to manage the addition of builtin operator overload
7221/// candidates. It provides shared state and utility methods used throughout
7222/// the process, as well as a helper method to add each group of builtin
7223/// operator overloads from the standard to a candidate set.
7224class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007225 // Common instance state available to all overload candidate addition methods.
7226 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007227 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007228 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007229 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007230 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007231 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007232
Chandler Carruthc6586e52010-12-12 10:35:00 +00007233 // Define some constants used to index and iterate over the arithemetic types
7234 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007235 // The "promoted arithmetic types" are the arithmetic
7236 // types are that preserved by promotion (C++ [over.built]p2).
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007237 static const unsigned FirstIntegralType = 4;
7238 static const unsigned LastIntegralType = 21;
7239 static const unsigned FirstPromotedIntegralType = 4,
7240 LastPromotedIntegralType = 12;
John McCall52872982010-11-13 05:51:15 +00007241 static const unsigned FirstPromotedArithmeticType = 0,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007242 LastPromotedArithmeticType = 12;
7243 static const unsigned NumArithmeticTypes = 21;
John McCall52872982010-11-13 05:51:15 +00007244
Chandler Carruthc6586e52010-12-12 10:35:00 +00007245 /// \brief Get the canonical type for a given arithmetic type index.
7246 CanQualType getArithmeticType(unsigned index) {
7247 assert(index < NumArithmeticTypes);
7248 static CanQualType ASTContext::* const
7249 ArithmeticTypes[NumArithmeticTypes] = {
7250 // Start of promoted types.
7251 &ASTContext::FloatTy,
7252 &ASTContext::DoubleTy,
7253 &ASTContext::LongDoubleTy,
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007254 &ASTContext::Float128Ty,
John McCall52872982010-11-13 05:51:15 +00007255
Chandler Carruthc6586e52010-12-12 10:35:00 +00007256 // Start of integral types.
7257 &ASTContext::IntTy,
7258 &ASTContext::LongTy,
7259 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007260 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007261 &ASTContext::UnsignedIntTy,
7262 &ASTContext::UnsignedLongTy,
7263 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007264 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007265 // End of promoted types.
7266
7267 &ASTContext::BoolTy,
7268 &ASTContext::CharTy,
7269 &ASTContext::WCharTy,
7270 &ASTContext::Char16Ty,
7271 &ASTContext::Char32Ty,
7272 &ASTContext::SignedCharTy,
7273 &ASTContext::ShortTy,
7274 &ASTContext::UnsignedCharTy,
7275 &ASTContext::UnsignedShortTy,
7276 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007277 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007278 };
7279 return S.Context.*ArithmeticTypes[index];
7280 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007281
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007282 /// \brief Gets the canonical type resulting from the usual arithemetic
7283 /// converions for the given arithmetic types.
7284 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7285 // Accelerator table for performing the usual arithmetic conversions.
7286 // The rules are basically:
7287 // - if either is floating-point, use the wider floating-point
7288 // - if same signedness, use the higher rank
7289 // - if same size, use unsigned of the higher rank
7290 // - use the larger type
7291 // These rules, together with the axiom that higher ranks are
7292 // never smaller, are sufficient to precompute all of these results
7293 // *except* when dealing with signed types of higher rank.
7294 // (we could precompute SLL x UI for all known platforms, but it's
7295 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007296 // We assume that int128 has a higher rank than long long on all platforms.
George Burgess IVf23ce362016-04-29 21:32:53 +00007297 enum PromotedType : int8_t {
Richard Smith521ecc12012-06-10 08:00:26 +00007298 Dep=-1,
7299 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007300 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007301 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007302 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007303/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7304/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7305/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7306/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7307/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7308/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7309/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7310/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7311/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7312/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7313/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007314 };
7315
7316 assert(L < LastPromotedArithmeticType);
7317 assert(R < LastPromotedArithmeticType);
7318 int Idx = ConversionsTable[L][R];
7319
7320 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007321 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007322
7323 // Slow path: we need to compare widths.
7324 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007325 CanQualType LT = getArithmeticType(L),
7326 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007327 unsigned LW = S.Context.getIntWidth(LT),
7328 RW = S.Context.getIntWidth(RT);
7329
7330 // If they're different widths, use the signed type.
7331 if (LW > RW) return LT;
7332 else if (LW < RW) return RT;
7333
7334 // Otherwise, use the unsigned type of the signed type's rank.
7335 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7336 assert(L == SLL || R == SLL);
7337 return S.Context.UnsignedLongLongTy;
7338 }
7339
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007340 /// \brief Helper method to factor out the common pattern of adding overloads
7341 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007342 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007343 bool HasVolatile,
7344 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007345 QualType ParamTypes[2] = {
7346 S.Context.getLValueReferenceType(CandidateTy),
7347 S.Context.IntTy
7348 };
7349
7350 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007351 if (Args.size() == 1)
7352 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007353 else
Richard Smithe54c3072013-05-05 15:51:06 +00007354 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007355
7356 // Use a heuristic to reduce number of builtin candidates in the set:
7357 // add volatile version only if there are conversions to a volatile type.
7358 if (HasVolatile) {
7359 ParamTypes[0] =
7360 S.Context.getLValueReferenceType(
7361 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007362 if (Args.size() == 1)
7363 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007364 else
Richard Smithe54c3072013-05-05 15:51:06 +00007365 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007366 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007367
7368 // Add restrict version only if there are conversions to a restrict type
7369 // and our candidate type is a non-restrict-qualified pointer.
7370 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7371 !CandidateTy.isRestrictQualified()) {
7372 ParamTypes[0]
7373 = S.Context.getLValueReferenceType(
7374 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007375 if (Args.size() == 1)
7376 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007377 else
Richard Smithe54c3072013-05-05 15:51:06 +00007378 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007379
7380 if (HasVolatile) {
7381 ParamTypes[0]
7382 = S.Context.getLValueReferenceType(
7383 S.Context.getCVRQualifiedType(CandidateTy,
7384 (Qualifiers::Volatile |
7385 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007386 if (Args.size() == 1)
7387 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007388 else
Richard Smithe54c3072013-05-05 15:51:06 +00007389 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007390 }
7391 }
7392
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007393 }
7394
7395public:
7396 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007397 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007398 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007399 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007400 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007401 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007402 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007403 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007404 HasArithmeticOrEnumeralCandidateType(
7405 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007406 CandidateTypes(CandidateTypes),
7407 CandidateSet(CandidateSet) {
7408 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007409 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007410 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007411 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007412 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007413 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007414 assert(getArithmeticType(FirstPromotedArithmeticType)
7415 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007416 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007417 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007418 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007419 "Invalid last promoted arithmetic type");
7420 }
7421
7422 // C++ [over.built]p3:
7423 //
7424 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7425 // is either volatile or empty, there exist candidate operator
7426 // functions of the form
7427 //
7428 // VQ T& operator++(VQ T&);
7429 // T operator++(VQ T&, int);
7430 //
7431 // C++ [over.built]p4:
7432 //
7433 // For every pair (T, VQ), where T is an arithmetic type other
7434 // than bool, and VQ is either volatile or empty, there exist
7435 // candidate operator functions of the form
7436 //
7437 // VQ T& operator--(VQ T&);
7438 // T operator--(VQ T&, int);
7439 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007440 if (!HasArithmeticOrEnumeralCandidateType)
7441 return;
7442
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007443 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7444 Arith < NumArithmeticTypes; ++Arith) {
7445 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007446 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007447 VisibleTypeConversionsQuals.hasVolatile(),
7448 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007449 }
7450 }
7451
7452 // C++ [over.built]p5:
7453 //
7454 // For every pair (T, VQ), where T is a cv-qualified or
7455 // cv-unqualified object type, and VQ is either volatile or
7456 // empty, there exist candidate operator functions of the form
7457 //
7458 // T*VQ& operator++(T*VQ&);
7459 // T*VQ& operator--(T*VQ&);
7460 // T* operator++(T*VQ&, int);
7461 // T* operator--(T*VQ&, int);
7462 void addPlusPlusMinusMinusPointerOverloads() {
7463 for (BuiltinCandidateTypeSet::iterator
7464 Ptr = CandidateTypes[0].pointer_begin(),
7465 PtrEnd = CandidateTypes[0].pointer_end();
7466 Ptr != PtrEnd; ++Ptr) {
7467 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007468 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007469 continue;
7470
7471 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007472 (!(*Ptr).isVolatileQualified() &&
7473 VisibleTypeConversionsQuals.hasVolatile()),
7474 (!(*Ptr).isRestrictQualified() &&
7475 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007476 }
7477 }
7478
7479 // C++ [over.built]p6:
7480 // For every cv-qualified or cv-unqualified object type T, there
7481 // exist candidate operator functions of the form
7482 //
7483 // T& operator*(T*);
7484 //
7485 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007486 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007487 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007488 // T& operator*(T*);
7489 void addUnaryStarPointerOverloads() {
7490 for (BuiltinCandidateTypeSet::iterator
7491 Ptr = CandidateTypes[0].pointer_begin(),
7492 PtrEnd = CandidateTypes[0].pointer_end();
7493 Ptr != PtrEnd; ++Ptr) {
7494 QualType ParamTy = *Ptr;
7495 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007496 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7497 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007498
Douglas Gregor02824322011-01-26 19:30:28 +00007499 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7500 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7501 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007502
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007503 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007504 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007505 }
7506 }
7507
7508 // C++ [over.built]p9:
7509 // For every promoted arithmetic type T, there exist candidate
7510 // operator functions of the form
7511 //
7512 // T operator+(T);
7513 // T operator-(T);
7514 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007515 if (!HasArithmeticOrEnumeralCandidateType)
7516 return;
7517
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007518 for (unsigned Arith = FirstPromotedArithmeticType;
7519 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007520 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007521 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007522 }
7523
7524 // Extension: We also add these operators for vector types.
7525 for (BuiltinCandidateTypeSet::iterator
7526 Vec = CandidateTypes[0].vector_begin(),
7527 VecEnd = CandidateTypes[0].vector_end();
7528 Vec != VecEnd; ++Vec) {
7529 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007530 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007531 }
7532 }
7533
7534 // C++ [over.built]p8:
7535 // For every type T, there exist candidate operator functions of
7536 // the form
7537 //
7538 // T* operator+(T*);
7539 void addUnaryPlusPointerOverloads() {
7540 for (BuiltinCandidateTypeSet::iterator
7541 Ptr = CandidateTypes[0].pointer_begin(),
7542 PtrEnd = CandidateTypes[0].pointer_end();
7543 Ptr != PtrEnd; ++Ptr) {
7544 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007545 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007546 }
7547 }
7548
7549 // C++ [over.built]p10:
7550 // For every promoted integral type T, there exist candidate
7551 // operator functions of the form
7552 //
7553 // T operator~(T);
7554 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007555 if (!HasArithmeticOrEnumeralCandidateType)
7556 return;
7557
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007558 for (unsigned Int = FirstPromotedIntegralType;
7559 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007560 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007561 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007562 }
7563
7564 // Extension: We also add this operator for vector types.
7565 for (BuiltinCandidateTypeSet::iterator
7566 Vec = CandidateTypes[0].vector_begin(),
7567 VecEnd = CandidateTypes[0].vector_end();
7568 Vec != VecEnd; ++Vec) {
7569 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007570 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007571 }
7572 }
7573
7574 // C++ [over.match.oper]p16:
7575 // For every pointer to member type T, there exist candidate operator
7576 // functions of the form
7577 //
7578 // bool operator==(T,T);
7579 // bool operator!=(T,T);
7580 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7581 /// Set of (canonical) types that we've already handled.
7582 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7583
Richard Smithe54c3072013-05-05 15:51:06 +00007584 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007585 for (BuiltinCandidateTypeSet::iterator
7586 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7587 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7588 MemPtr != MemPtrEnd;
7589 ++MemPtr) {
7590 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007591 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007592 continue;
7593
7594 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007595 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007596 }
7597 }
7598 }
7599
7600 // C++ [over.built]p15:
7601 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007602 // For every T, where T is an enumeration type, a pointer type, or
7603 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007604 //
7605 // bool operator<(T, T);
7606 // bool operator>(T, T);
7607 // bool operator<=(T, T);
7608 // bool operator>=(T, T);
7609 // bool operator==(T, T);
7610 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007611 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007612 // C++ [over.match.oper]p3:
7613 // [...]the built-in candidates include all of the candidate operator
7614 // functions defined in 13.6 that, compared to the given operator, [...]
7615 // do not have the same parameter-type-list as any non-template non-member
7616 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007617 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007618 // Note that in practice, this only affects enumeration types because there
7619 // aren't any built-in candidates of record type, and a user-defined operator
7620 // must have an operand of record or enumeration type. Also, the only other
7621 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007622 // cannot be overloaded for enumeration types, so this is the only place
7623 // where we must suppress candidates like this.
7624 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7625 UserDefinedBinaryOperators;
7626
Richard Smithe54c3072013-05-05 15:51:06 +00007627 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007628 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7629 CandidateTypes[ArgIdx].enumeration_end()) {
7630 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7631 CEnd = CandidateSet.end();
7632 C != CEnd; ++C) {
7633 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7634 continue;
7635
Eli Friedman14f082b2012-09-18 21:52:24 +00007636 if (C->Function->isFunctionTemplateSpecialization())
7637 continue;
7638
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007639 QualType FirstParamType =
7640 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7641 QualType SecondParamType =
7642 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7643
7644 // Skip if either parameter isn't of enumeral type.
7645 if (!FirstParamType->isEnumeralType() ||
7646 !SecondParamType->isEnumeralType())
7647 continue;
7648
7649 // Add this operator to the set of known user-defined operators.
7650 UserDefinedBinaryOperators.insert(
7651 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7652 S.Context.getCanonicalType(SecondParamType)));
7653 }
7654 }
7655 }
7656
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007657 /// Set of (canonical) types that we've already handled.
7658 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7659
Richard Smithe54c3072013-05-05 15:51:06 +00007660 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007661 for (BuiltinCandidateTypeSet::iterator
7662 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7663 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7664 Ptr != PtrEnd; ++Ptr) {
7665 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007666 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007667 continue;
7668
7669 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007670 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007671 }
7672 for (BuiltinCandidateTypeSet::iterator
7673 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7674 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7675 Enum != EnumEnd; ++Enum) {
7676 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7677
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007678 // Don't add the same builtin candidate twice, or if a user defined
7679 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007680 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007681 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7682 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007683 continue;
7684
7685 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007686 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007687 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007688
7689 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7690 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007691 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007692 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007693 NullPtrTy))) {
7694 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007695 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007696 CandidateSet);
7697 }
7698 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007699 }
7700 }
7701
7702 // C++ [over.built]p13:
7703 //
7704 // For every cv-qualified or cv-unqualified object type T
7705 // there exist candidate operator functions of the form
7706 //
7707 // T* operator+(T*, ptrdiff_t);
7708 // T& operator[](T*, ptrdiff_t); [BELOW]
7709 // T* operator-(T*, ptrdiff_t);
7710 // T* operator+(ptrdiff_t, T*);
7711 // T& operator[](ptrdiff_t, T*); [BELOW]
7712 //
7713 // C++ [over.built]p14:
7714 //
7715 // For every T, where T is a pointer to object type, there
7716 // exist candidate operator functions of the form
7717 //
7718 // ptrdiff_t operator-(T, T);
7719 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7720 /// Set of (canonical) types that we've already handled.
7721 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7722
7723 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007724 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007725 S.Context.getPointerDiffType(),
7726 S.Context.getPointerDiffType(),
7727 };
7728 for (BuiltinCandidateTypeSet::iterator
7729 Ptr = CandidateTypes[Arg].pointer_begin(),
7730 PtrEnd = CandidateTypes[Arg].pointer_end();
7731 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007732 QualType PointeeTy = (*Ptr)->getPointeeType();
7733 if (!PointeeTy->isObjectType())
7734 continue;
7735
Eric Christopher9207a522015-08-21 16:24:01 +00007736 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007737 if (Arg == 0 || Op == OO_Plus) {
7738 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7739 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007740 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007741 }
7742 if (Op == OO_Minus) {
7743 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007744 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007745 continue;
7746
7747 QualType ParamTypes[2] = { *Ptr, *Ptr };
7748 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007749 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007750 }
7751 }
7752 }
7753 }
7754
7755 // C++ [over.built]p12:
7756 //
7757 // For every pair of promoted arithmetic types L and R, there
7758 // exist candidate operator functions of the form
7759 //
7760 // LR operator*(L, R);
7761 // LR operator/(L, R);
7762 // LR operator+(L, R);
7763 // LR operator-(L, R);
7764 // bool operator<(L, R);
7765 // bool operator>(L, R);
7766 // bool operator<=(L, R);
7767 // bool operator>=(L, R);
7768 // bool operator==(L, R);
7769 // bool operator!=(L, R);
7770 //
7771 // where LR is the result of the usual arithmetic conversions
7772 // between types L and R.
7773 //
7774 // C++ [over.built]p24:
7775 //
7776 // For every pair of promoted arithmetic types L and R, there exist
7777 // candidate operator functions of the form
7778 //
7779 // LR operator?(bool, L, R);
7780 //
7781 // where LR is the result of the usual arithmetic conversions
7782 // between types L and R.
7783 // Our candidates ignore the first parameter.
7784 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007785 if (!HasArithmeticOrEnumeralCandidateType)
7786 return;
7787
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007788 for (unsigned Left = FirstPromotedArithmeticType;
7789 Left < LastPromotedArithmeticType; ++Left) {
7790 for (unsigned Right = FirstPromotedArithmeticType;
7791 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007792 QualType LandR[2] = { getArithmeticType(Left),
7793 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007794 QualType Result =
7795 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007796 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007797 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007798 }
7799 }
7800
7801 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7802 // conditional operator for vector types.
7803 for (BuiltinCandidateTypeSet::iterator
7804 Vec1 = CandidateTypes[0].vector_begin(),
7805 Vec1End = CandidateTypes[0].vector_end();
7806 Vec1 != Vec1End; ++Vec1) {
7807 for (BuiltinCandidateTypeSet::iterator
7808 Vec2 = CandidateTypes[1].vector_begin(),
7809 Vec2End = CandidateTypes[1].vector_end();
7810 Vec2 != Vec2End; ++Vec2) {
7811 QualType LandR[2] = { *Vec1, *Vec2 };
7812 QualType Result = S.Context.BoolTy;
7813 if (!isComparison) {
7814 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7815 Result = *Vec1;
7816 else
7817 Result = *Vec2;
7818 }
7819
Richard Smithe54c3072013-05-05 15:51:06 +00007820 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007821 }
7822 }
7823 }
7824
7825 // C++ [over.built]p17:
7826 //
7827 // For every pair of promoted integral types L and R, there
7828 // exist candidate operator functions of the form
7829 //
7830 // LR operator%(L, R);
7831 // LR operator&(L, R);
7832 // LR operator^(L, R);
7833 // LR operator|(L, R);
7834 // L operator<<(L, R);
7835 // L operator>>(L, R);
7836 //
7837 // where LR is the result of the usual arithmetic conversions
7838 // between types L and R.
7839 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007840 if (!HasArithmeticOrEnumeralCandidateType)
7841 return;
7842
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007843 for (unsigned Left = FirstPromotedIntegralType;
7844 Left < LastPromotedIntegralType; ++Left) {
7845 for (unsigned Right = FirstPromotedIntegralType;
7846 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007847 QualType LandR[2] = { getArithmeticType(Left),
7848 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007849 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7850 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007851 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007852 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007853 }
7854 }
7855 }
7856
7857 // C++ [over.built]p20:
7858 //
7859 // For every pair (T, VQ), where T is an enumeration or
7860 // pointer to member type and VQ is either volatile or
7861 // empty, there exist candidate operator functions of the form
7862 //
7863 // VQ T& operator=(VQ T&, T);
7864 void addAssignmentMemberPointerOrEnumeralOverloads() {
7865 /// Set of (canonical) types that we've already handled.
7866 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7867
7868 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7869 for (BuiltinCandidateTypeSet::iterator
7870 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7871 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7872 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007873 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007874 continue;
7875
Richard Smithe54c3072013-05-05 15:51:06 +00007876 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007877 }
7878
7879 for (BuiltinCandidateTypeSet::iterator
7880 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7881 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7882 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007883 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007884 continue;
7885
Richard Smithe54c3072013-05-05 15:51:06 +00007886 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007887 }
7888 }
7889 }
7890
7891 // C++ [over.built]p19:
7892 //
7893 // For every pair (T, VQ), where T is any type and VQ is either
7894 // volatile or empty, there exist candidate operator functions
7895 // of the form
7896 //
7897 // T*VQ& operator=(T*VQ&, T*);
7898 //
7899 // C++ [over.built]p21:
7900 //
7901 // For every pair (T, VQ), where T is a cv-qualified or
7902 // cv-unqualified object type and VQ is either volatile or
7903 // empty, there exist candidate operator functions of the form
7904 //
7905 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7906 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7907 void addAssignmentPointerOverloads(bool isEqualOp) {
7908 /// Set of (canonical) types that we've already handled.
7909 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7910
7911 for (BuiltinCandidateTypeSet::iterator
7912 Ptr = CandidateTypes[0].pointer_begin(),
7913 PtrEnd = CandidateTypes[0].pointer_end();
7914 Ptr != PtrEnd; ++Ptr) {
7915 // If this is operator=, keep track of the builtin candidates we added.
7916 if (isEqualOp)
7917 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007918 else if (!(*Ptr)->getPointeeType()->isObjectType())
7919 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007920
7921 // non-volatile version
7922 QualType ParamTypes[2] = {
7923 S.Context.getLValueReferenceType(*Ptr),
7924 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7925 };
Richard Smithe54c3072013-05-05 15:51:06 +00007926 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007927 /*IsAssigmentOperator=*/ isEqualOp);
7928
Douglas Gregor5bee2582012-06-04 00:15:09 +00007929 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7930 VisibleTypeConversionsQuals.hasVolatile();
7931 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007932 // volatile version
7933 ParamTypes[0] =
7934 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007935 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007936 /*IsAssigmentOperator=*/isEqualOp);
7937 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007938
7939 if (!(*Ptr).isRestrictQualified() &&
7940 VisibleTypeConversionsQuals.hasRestrict()) {
7941 // restrict version
7942 ParamTypes[0]
7943 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007944 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007945 /*IsAssigmentOperator=*/isEqualOp);
7946
7947 if (NeedVolatile) {
7948 // volatile restrict version
7949 ParamTypes[0]
7950 = S.Context.getLValueReferenceType(
7951 S.Context.getCVRQualifiedType(*Ptr,
7952 (Qualifiers::Volatile |
7953 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007954 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007955 /*IsAssigmentOperator=*/isEqualOp);
7956 }
7957 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007958 }
7959
7960 if (isEqualOp) {
7961 for (BuiltinCandidateTypeSet::iterator
7962 Ptr = CandidateTypes[1].pointer_begin(),
7963 PtrEnd = CandidateTypes[1].pointer_end();
7964 Ptr != PtrEnd; ++Ptr) {
7965 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007966 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007967 continue;
7968
Chandler Carruth8e543b32010-12-12 08:17:55 +00007969 QualType ParamTypes[2] = {
7970 S.Context.getLValueReferenceType(*Ptr),
7971 *Ptr,
7972 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007973
7974 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007975 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007976 /*IsAssigmentOperator=*/true);
7977
Douglas Gregor5bee2582012-06-04 00:15:09 +00007978 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7979 VisibleTypeConversionsQuals.hasVolatile();
7980 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007981 // volatile version
7982 ParamTypes[0] =
7983 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007984 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7985 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007986 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007987
7988 if (!(*Ptr).isRestrictQualified() &&
7989 VisibleTypeConversionsQuals.hasRestrict()) {
7990 // restrict version
7991 ParamTypes[0]
7992 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007993 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7994 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007995
7996 if (NeedVolatile) {
7997 // volatile restrict version
7998 ParamTypes[0]
7999 = S.Context.getLValueReferenceType(
8000 S.Context.getCVRQualifiedType(*Ptr,
8001 (Qualifiers::Volatile |
8002 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00008003 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8004 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00008005 }
8006 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008007 }
8008 }
8009 }
8010
8011 // C++ [over.built]p18:
8012 //
8013 // For every triple (L, VQ, R), where L is an arithmetic type,
8014 // VQ is either volatile or empty, and R is a promoted
8015 // arithmetic type, there exist candidate operator functions of
8016 // the form
8017 //
8018 // VQ L& operator=(VQ L&, R);
8019 // VQ L& operator*=(VQ L&, R);
8020 // VQ L& operator/=(VQ L&, R);
8021 // VQ L& operator+=(VQ L&, R);
8022 // VQ L& operator-=(VQ L&, R);
8023 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00008024 if (!HasArithmeticOrEnumeralCandidateType)
8025 return;
8026
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008027 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8028 for (unsigned Right = FirstPromotedArithmeticType;
8029 Right < LastPromotedArithmeticType; ++Right) {
8030 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008031 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008032
8033 // Add this built-in operator as a candidate (VQ is empty).
8034 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008035 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008036 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008037 /*IsAssigmentOperator=*/isEqualOp);
8038
8039 // Add this built-in operator as a candidate (VQ is 'volatile').
8040 if (VisibleTypeConversionsQuals.hasVolatile()) {
8041 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008042 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008043 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008044 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008045 /*IsAssigmentOperator=*/isEqualOp);
8046 }
8047 }
8048 }
8049
8050 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8051 for (BuiltinCandidateTypeSet::iterator
8052 Vec1 = CandidateTypes[0].vector_begin(),
8053 Vec1End = CandidateTypes[0].vector_end();
8054 Vec1 != Vec1End; ++Vec1) {
8055 for (BuiltinCandidateTypeSet::iterator
8056 Vec2 = CandidateTypes[1].vector_begin(),
8057 Vec2End = CandidateTypes[1].vector_end();
8058 Vec2 != Vec2End; ++Vec2) {
8059 QualType ParamTypes[2];
8060 ParamTypes[1] = *Vec2;
8061 // Add this built-in operator as a candidate (VQ is empty).
8062 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00008063 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008064 /*IsAssigmentOperator=*/isEqualOp);
8065
8066 // Add this built-in operator as a candidate (VQ is 'volatile').
8067 if (VisibleTypeConversionsQuals.hasVolatile()) {
8068 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8069 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008070 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008071 /*IsAssigmentOperator=*/isEqualOp);
8072 }
8073 }
8074 }
8075 }
8076
8077 // C++ [over.built]p22:
8078 //
8079 // For every triple (L, VQ, R), where L is an integral type, VQ
8080 // is either volatile or empty, and R is a promoted integral
8081 // type, there exist candidate operator functions of the form
8082 //
8083 // VQ L& operator%=(VQ L&, R);
8084 // VQ L& operator<<=(VQ L&, R);
8085 // VQ L& operator>>=(VQ L&, R);
8086 // VQ L& operator&=(VQ L&, R);
8087 // VQ L& operator^=(VQ L&, R);
8088 // VQ L& operator|=(VQ L&, R);
8089 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00008090 if (!HasArithmeticOrEnumeralCandidateType)
8091 return;
8092
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008093 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8094 for (unsigned Right = FirstPromotedIntegralType;
8095 Right < LastPromotedIntegralType; ++Right) {
8096 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00008097 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008098
8099 // Add this built-in operator as a candidate (VQ is empty).
8100 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00008101 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00008102 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008103 if (VisibleTypeConversionsQuals.hasVolatile()) {
8104 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00008105 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008106 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8107 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00008108 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008109 }
8110 }
8111 }
8112 }
8113
8114 // C++ [over.operator]p23:
8115 //
8116 // There also exist candidate operator functions of the form
8117 //
8118 // bool operator!(bool);
8119 // bool operator&&(bool, bool);
8120 // bool operator||(bool, bool);
8121 void addExclaimOverload() {
8122 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00008123 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008124 /*IsAssignmentOperator=*/false,
8125 /*NumContextualBoolArguments=*/1);
8126 }
8127 void addAmpAmpOrPipePipeOverload() {
8128 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00008129 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008130 /*IsAssignmentOperator=*/false,
8131 /*NumContextualBoolArguments=*/2);
8132 }
8133
8134 // C++ [over.built]p13:
8135 //
8136 // For every cv-qualified or cv-unqualified object type T there
8137 // exist candidate operator functions of the form
8138 //
8139 // T* operator+(T*, ptrdiff_t); [ABOVE]
8140 // T& operator[](T*, ptrdiff_t);
8141 // T* operator-(T*, ptrdiff_t); [ABOVE]
8142 // T* operator+(ptrdiff_t, T*); [ABOVE]
8143 // T& operator[](ptrdiff_t, T*);
8144 void addSubscriptOverloads() {
8145 for (BuiltinCandidateTypeSet::iterator
8146 Ptr = CandidateTypes[0].pointer_begin(),
8147 PtrEnd = CandidateTypes[0].pointer_end();
8148 Ptr != PtrEnd; ++Ptr) {
8149 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8150 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008151 if (!PointeeType->isObjectType())
8152 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008153
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008154 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8155
8156 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00008157 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008158 }
8159
8160 for (BuiltinCandidateTypeSet::iterator
8161 Ptr = CandidateTypes[1].pointer_begin(),
8162 PtrEnd = CandidateTypes[1].pointer_end();
8163 Ptr != PtrEnd; ++Ptr) {
8164 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8165 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008166 if (!PointeeType->isObjectType())
8167 continue;
8168
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008169 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8170
8171 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008172 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008173 }
8174 }
8175
8176 // C++ [over.built]p11:
8177 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8178 // C1 is the same type as C2 or is a derived class of C2, T is an object
8179 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8180 // there exist candidate operator functions of the form
8181 //
8182 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8183 //
8184 // where CV12 is the union of CV1 and CV2.
8185 void addArrowStarOverloads() {
8186 for (BuiltinCandidateTypeSet::iterator
8187 Ptr = CandidateTypes[0].pointer_begin(),
8188 PtrEnd = CandidateTypes[0].pointer_end();
8189 Ptr != PtrEnd; ++Ptr) {
8190 QualType C1Ty = (*Ptr);
8191 QualType C1;
8192 QualifierCollector Q1;
8193 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8194 if (!isa<RecordType>(C1))
8195 continue;
8196 // heuristic to reduce number of builtin candidates in the set.
8197 // Add volatile/restrict version only if there are conversions to a
8198 // volatile/restrict type.
8199 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8200 continue;
8201 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8202 continue;
8203 for (BuiltinCandidateTypeSet::iterator
8204 MemPtr = CandidateTypes[1].member_pointer_begin(),
8205 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8206 MemPtr != MemPtrEnd; ++MemPtr) {
8207 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8208 QualType C2 = QualType(mptr->getClass(), 0);
8209 C2 = C2.getUnqualifiedType();
Richard Smith0f59cb32015-12-18 21:45:41 +00008210 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008211 break;
8212 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8213 // build CV12 T&
8214 QualType T = mptr->getPointeeType();
8215 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8216 T.isVolatileQualified())
8217 continue;
8218 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8219 T.isRestrictQualified())
8220 continue;
8221 T = Q1.apply(S.Context, T);
8222 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008223 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008224 }
8225 }
8226 }
8227
8228 // Note that we don't consider the first argument, since it has been
8229 // contextually converted to bool long ago. The candidates below are
8230 // therefore added as binary.
8231 //
8232 // C++ [over.built]p25:
8233 // For every type T, where T is a pointer, pointer-to-member, or scoped
8234 // enumeration type, there exist candidate operator functions of the form
8235 //
8236 // T operator?(bool, T, T);
8237 //
8238 void addConditionalOperatorOverloads() {
8239 /// Set of (canonical) types that we've already handled.
8240 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8241
8242 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8243 for (BuiltinCandidateTypeSet::iterator
8244 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8245 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8246 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008247 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008248 continue;
8249
8250 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008251 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008252 }
8253
8254 for (BuiltinCandidateTypeSet::iterator
8255 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8256 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8257 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008258 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008259 continue;
8260
8261 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008262 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008263 }
8264
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008265 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008266 for (BuiltinCandidateTypeSet::iterator
8267 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8268 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8269 Enum != EnumEnd; ++Enum) {
8270 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8271 continue;
8272
David Blaikie82e95a32014-11-19 07:49:47 +00008273 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008274 continue;
8275
8276 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008277 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008278 }
8279 }
8280 }
8281 }
8282};
8283
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008284} // end anonymous namespace
8285
8286/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8287/// operator overloads to the candidate set (C++ [over.built]), based
8288/// on the operator @p Op and the arguments given. For example, if the
8289/// operator is a binary '+', this routine might add "int
8290/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008291void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8292 SourceLocation OpLoc,
8293 ArrayRef<Expr *> Args,
8294 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008295 // Find all of the types that the arguments can convert to, but only
8296 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008297 // that make use of these types. Also record whether we encounter non-record
8298 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008299 Qualifiers VisibleTypeConversionsQuals;
8300 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008301 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008302 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008303
8304 bool HasNonRecordCandidateType = false;
8305 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008306 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008307 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008308 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008309 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8310 OpLoc,
8311 true,
8312 (Op == OO_Exclaim ||
8313 Op == OO_AmpAmp ||
8314 Op == OO_PipePipe),
8315 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008316 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8317 CandidateTypes[ArgIdx].hasNonRecordTypes();
8318 HasArithmeticOrEnumeralCandidateType =
8319 HasArithmeticOrEnumeralCandidateType ||
8320 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008321 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008322
Chandler Carruth00a38332010-12-13 01:44:01 +00008323 // Exit early when no non-record types have been added to the candidate set
8324 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008325 //
8326 // We can't exit early for !, ||, or &&, since there we have always have
8327 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008328 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008329 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008330 return;
8331
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008332 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008333 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008334 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008335 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008336 CandidateTypes, CandidateSet);
8337
8338 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008339 switch (Op) {
8340 case OO_None:
8341 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008342 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008343
Chandler Carruth5184de02010-12-12 08:51:33 +00008344 case OO_New:
8345 case OO_Delete:
8346 case OO_Array_New:
8347 case OO_Array_Delete:
8348 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008349 llvm_unreachable(
8350 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008351
8352 case OO_Comma:
8353 case OO_Arrow:
Richard Smith9f690bd2015-10-27 06:02:45 +00008354 case OO_Coawait:
Chandler Carruth5184de02010-12-12 08:51:33 +00008355 // C++ [over.match.oper]p3:
Richard Smith9f690bd2015-10-27 06:02:45 +00008356 // -- For the operator ',', the unary operator '&', the
8357 // operator '->', or the operator 'co_await', the
8358 // built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008359 break;
8360
8361 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008362 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008363 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008364 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008365
8366 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008367 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008368 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008369 } else {
8370 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8371 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8372 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008373 break;
8374
Chandler Carruth5184de02010-12-12 08:51:33 +00008375 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008376 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008377 OpBuilder.addUnaryStarPointerOverloads();
8378 else
8379 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8380 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008381
Chandler Carruth5184de02010-12-12 08:51:33 +00008382 case OO_Slash:
8383 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008384 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008385
8386 case OO_PlusPlus:
8387 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008388 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8389 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008390 break;
8391
Douglas Gregor84605ae2009-08-24 13:43:27 +00008392 case OO_EqualEqual:
8393 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008394 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008395 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008396
Douglas Gregora11693b2008-11-12 17:17:38 +00008397 case OO_Less:
8398 case OO_Greater:
8399 case OO_LessEqual:
8400 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008401 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008402 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8403 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008404
Douglas Gregora11693b2008-11-12 17:17:38 +00008405 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008406 case OO_Caret:
8407 case OO_Pipe:
8408 case OO_LessLess:
8409 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008410 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008411 break;
8412
Chandler Carruth5184de02010-12-12 08:51:33 +00008413 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008414 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008415 // C++ [over.match.oper]p3:
8416 // -- For the operator ',', the unary operator '&', or the
8417 // operator '->', the built-in candidates set is empty.
8418 break;
8419
8420 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8421 break;
8422
8423 case OO_Tilde:
8424 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8425 break;
8426
Douglas Gregora11693b2008-11-12 17:17:38 +00008427 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008428 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008429 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008430
8431 case OO_PlusEqual:
8432 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008433 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008434 // Fall through.
8435
8436 case OO_StarEqual:
8437 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008438 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008439 break;
8440
8441 case OO_PercentEqual:
8442 case OO_LessLessEqual:
8443 case OO_GreaterGreaterEqual:
8444 case OO_AmpEqual:
8445 case OO_CaretEqual:
8446 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008447 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008448 break;
8449
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008450 case OO_Exclaim:
8451 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008452 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008453
Douglas Gregora11693b2008-11-12 17:17:38 +00008454 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008455 case OO_PipePipe:
8456 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008457 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008458
8459 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008460 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008461 break;
8462
8463 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008464 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008465 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008466
8467 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008468 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008469 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8470 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008471 }
8472}
8473
Douglas Gregore254f902009-02-04 00:32:51 +00008474/// \brief Add function candidates found via argument-dependent lookup
8475/// to the set of overloading candidates.
8476///
8477/// This routine performs argument-dependent name lookup based on the
8478/// given function name (which may also be an operator name) and adds
8479/// all of the overload candidates found by ADL to the overload
8480/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008481void
Douglas Gregore254f902009-02-04 00:32:51 +00008482Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008483 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008484 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008485 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008486 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008487 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008488 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008489
John McCall91f61fc2010-01-26 06:04:06 +00008490 // FIXME: This approach for uniquing ADL results (and removing
8491 // redundant candidates from the set) relies on pointer-equality,
8492 // which means we need to key off the canonical decl. However,
8493 // always going back to the canonical decl might not get us the
8494 // right set of default arguments. What default arguments are
8495 // we supposed to consider on ADL candidates, anyway?
8496
Douglas Gregorcabea402009-09-22 15:41:20 +00008497 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008498 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008499
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008500 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008501 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8502 CandEnd = CandidateSet.end();
8503 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008504 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008505 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008506 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008507 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008508 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008509
8510 // For each of the ADL candidates we found, add it to the overload
8511 // set.
John McCall8fe68082010-01-26 07:16:45 +00008512 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008513 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008514 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008515 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008516 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008517
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008518 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8519 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008520 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008521 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008522 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008523 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008524 }
Douglas Gregore254f902009-02-04 00:32:51 +00008525}
8526
George Burgess IV3dc166912016-05-10 01:59:34 +00008527namespace {
8528enum class Comparison { Equal, Better, Worse };
8529}
8530
8531/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8532/// overload resolution.
8533///
8534/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8535/// Cand1's first N enable_if attributes have precisely the same conditions as
8536/// Cand2's first N enable_if attributes (where N = the number of enable_if
8537/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8538///
8539/// Note that you can have a pair of candidates such that Cand1's enable_if
8540/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8541/// worse than Cand1's.
8542static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8543 const FunctionDecl *Cand2) {
8544 // Common case: One (or both) decls don't have enable_if attrs.
8545 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8546 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8547 if (!Cand1Attr || !Cand2Attr) {
8548 if (Cand1Attr == Cand2Attr)
8549 return Comparison::Equal;
8550 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8551 }
George Burgess IV2a6150d2015-10-16 01:17:38 +00008552
8553 // FIXME: The next several lines are just
8554 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8555 // instead of reverse order which is how they're stored in the AST.
8556 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8557 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8558
George Burgess IV3dc166912016-05-10 01:59:34 +00008559 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8560 // has fewer enable_if attributes than Cand2.
8561 if (Cand1Attrs.size() < Cand2Attrs.size())
8562 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008563
8564 auto Cand1I = Cand1Attrs.begin();
8565 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8566 for (auto &Cand2A : Cand2Attrs) {
8567 Cand1ID.clear();
8568 Cand2ID.clear();
8569
8570 auto &Cand1A = *Cand1I++;
8571 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8572 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8573 if (Cand1ID != Cand2ID)
George Burgess IV3dc166912016-05-10 01:59:34 +00008574 return Comparison::Worse;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008575 }
8576
George Burgess IV3dc166912016-05-10 01:59:34 +00008577 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
George Burgess IV2a6150d2015-10-16 01:17:38 +00008578}
8579
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008580/// isBetterOverloadCandidate - Determines whether the first overload
8581/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008582bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8583 const OverloadCandidate &Cand2,
8584 SourceLocation Loc,
8585 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008586 // Define viable functions to be better candidates than non-viable
8587 // functions.
8588 if (!Cand2.Viable)
8589 return Cand1.Viable;
8590 else if (!Cand1.Viable)
8591 return false;
8592
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008593 // C++ [over.match.best]p1:
8594 //
8595 // -- if F is a static member function, ICS1(F) is defined such
8596 // that ICS1(F) is neither better nor worse than ICS1(G) for
8597 // any function G, and, symmetrically, ICS1(G) is neither
8598 // better nor worse than ICS1(F).
8599 unsigned StartArg = 0;
8600 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8601 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008602
George Burgess IVfbad5b22016-09-07 20:03:19 +00008603 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8604 // We don't allow incompatible pointer conversions in C++.
8605 if (!S.getLangOpts().CPlusPlus)
8606 return ICS.isStandard() &&
8607 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8608
8609 // The only ill-formed conversion we allow in C++ is the string literal to
8610 // char* conversion, which is only considered ill-formed after C++11.
8611 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8612 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8613 };
8614
8615 // Define functions that don't require ill-formed conversions for a given
8616 // argument to be better candidates than functions that do.
8617 unsigned NumArgs = Cand1.NumConversions;
8618 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8619 bool HasBetterConversion = false;
8620 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8621 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8622 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8623 if (Cand1Bad != Cand2Bad) {
8624 if (Cand1Bad)
8625 return false;
8626 HasBetterConversion = true;
8627 }
8628 }
8629
8630 if (HasBetterConversion)
8631 return true;
8632
Douglas Gregord3cb3562009-07-07 23:38:56 +00008633 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008634 // A viable function F1 is defined to be a better function than another
8635 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008636 // conversion sequence than ICSi(F2), and then...
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008637 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Richard Smith0f59cb32015-12-18 21:45:41 +00008638 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +00008639 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008640 Cand2.Conversions[ArgIdx])) {
8641 case ImplicitConversionSequence::Better:
8642 // Cand1 has a better conversion sequence.
8643 HasBetterConversion = true;
8644 break;
8645
8646 case ImplicitConversionSequence::Worse:
8647 // Cand1 can't be better than Cand2.
8648 return false;
8649
8650 case ImplicitConversionSequence::Indistinguishable:
8651 // Do nothing.
8652 break;
8653 }
8654 }
8655
Mike Stump11289f42009-09-09 15:08:12 +00008656 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008657 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008658 if (HasBetterConversion)
8659 return true;
8660
Douglas Gregora1f013e2008-11-07 22:36:19 +00008661 // -- the context is an initialization by user-defined conversion
8662 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8663 // from the return type of F1 to the destination type (i.e.,
8664 // the type of the entity being initialized) is a better
8665 // conversion sequence than the standard conversion sequence
8666 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008667 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008668 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008669 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008670 // First check whether we prefer one of the conversion functions over the
8671 // other. This only distinguishes the results in non-standard, extension
8672 // cases such as the conversion from a lambda closure type to a function
8673 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008674 ImplicitConversionSequence::CompareKind Result =
8675 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8676 if (Result == ImplicitConversionSequence::Indistinguishable)
Richard Smith0f59cb32015-12-18 21:45:41 +00008677 Result = CompareStandardConversionSequences(S, Loc,
Richard Smithec2748a2014-05-17 04:36:39 +00008678 Cand1.FinalConversion,
8679 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008680
Richard Smithec2748a2014-05-17 04:36:39 +00008681 if (Result != ImplicitConversionSequence::Indistinguishable)
8682 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008683
8684 // FIXME: Compare kind of reference binding if conversion functions
8685 // convert to a reference type used in direct reference binding, per
8686 // C++14 [over.match.best]p1 section 2 bullet 3.
8687 }
8688
8689 // -- F1 is a non-template function and F2 is a function template
8690 // specialization, or, if not that,
8691 bool Cand1IsSpecialization = Cand1.Function &&
8692 Cand1.Function->getPrimaryTemplate();
8693 bool Cand2IsSpecialization = Cand2.Function &&
8694 Cand2.Function->getPrimaryTemplate();
8695 if (Cand1IsSpecialization != Cand2IsSpecialization)
8696 return Cand2IsSpecialization;
8697
8698 // -- F1 and F2 are function template specializations, and the function
8699 // template for F1 is more specialized than the template for F2
8700 // according to the partial ordering rules described in 14.5.5.2, or,
8701 // if not that,
8702 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8703 if (FunctionTemplateDecl *BetterTemplate
8704 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8705 Cand2.Function->getPrimaryTemplate(),
8706 Loc,
8707 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8708 : TPOC_Call,
8709 Cand1.ExplicitCallArguments,
8710 Cand2.ExplicitCallArguments))
8711 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008712 }
8713
Richard Smith5179eb72016-06-28 19:03:57 +00008714 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8715 // A derived-class constructor beats an (inherited) base class constructor.
8716 bool Cand1IsInherited =
8717 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8718 bool Cand2IsInherited =
8719 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8720 if (Cand1IsInherited != Cand2IsInherited)
8721 return Cand2IsInherited;
8722 else if (Cand1IsInherited) {
8723 assert(Cand2IsInherited);
8724 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8725 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8726 if (Cand1Class->isDerivedFrom(Cand2Class))
8727 return true;
8728 if (Cand2Class->isDerivedFrom(Cand1Class))
8729 return false;
8730 // Inherited from sibling base classes: still ambiguous.
8731 }
8732
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008733 // Check for enable_if value-based overload resolution.
George Burgess IV3dc166912016-05-10 01:59:34 +00008734 if (Cand1.Function && Cand2.Function) {
8735 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8736 if (Cmp != Comparison::Equal)
8737 return Cmp == Comparison::Better;
8738 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008739
Justin Lebar25c4a812016-03-29 16:24:16 +00008740 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
Artem Belevich94a55e82015-09-22 17:22:59 +00008741 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8742 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8743 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8744 }
8745
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008746 bool HasPS1 = Cand1.Function != nullptr &&
8747 functionHasPassObjectSizeParams(Cand1.Function);
8748 bool HasPS2 = Cand2.Function != nullptr &&
8749 functionHasPassObjectSizeParams(Cand2.Function);
8750 return HasPS1 != HasPS2 && HasPS1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008751}
8752
Richard Smith2dbe4042015-11-04 19:26:32 +00008753/// Determine whether two declarations are "equivalent" for the purposes of
Richard Smith26210db2015-11-13 03:52:13 +00008754/// name lookup and overload resolution. This applies when the same internal/no
8755/// linkage entity is defined by two modules (probably by textually including
Richard Smith2dbe4042015-11-04 19:26:32 +00008756/// the same header). In such a case, we don't consider the declarations to
8757/// declare the same entity, but we also don't want lookups with both
8758/// declarations visible to be ambiguous in some cases (this happens when using
8759/// a modularized libstdc++).
8760bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8761 const NamedDecl *B) {
Richard Smith26210db2015-11-13 03:52:13 +00008762 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8763 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8764 if (!VA || !VB)
8765 return false;
8766
8767 // The declarations must be declaring the same name as an internal linkage
8768 // entity in different modules.
8769 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8770 VB->getDeclContext()->getRedeclContext()) ||
8771 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8772 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8773 VA->isExternallyVisible() || VB->isExternallyVisible())
8774 return false;
8775
8776 // Check that the declarations appear to be equivalent.
8777 //
8778 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8779 // For constants and functions, we should check the initializer or body is
8780 // the same. For non-constant variables, we shouldn't allow it at all.
8781 if (Context.hasSameType(VA->getType(), VB->getType()))
8782 return true;
8783
8784 // Enum constants within unnamed enumerations will have different types, but
8785 // may still be similar enough to be interchangeable for our purposes.
8786 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8787 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8788 // Only handle anonymous enums. If the enumerations were named and
8789 // equivalent, they would have been merged to the same type.
8790 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8791 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8792 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8793 !Context.hasSameType(EnumA->getIntegerType(),
8794 EnumB->getIntegerType()))
8795 return false;
8796 // Allow this only if the value is the same for both enumerators.
8797 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8798 }
8799 }
8800
8801 // Nothing else is sufficiently similar.
8802 return false;
Richard Smith2dbe4042015-11-04 19:26:32 +00008803}
8804
8805void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8806 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8807 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8808
8809 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8810 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8811 << !M << (M ? M->getFullModuleName() : "");
8812
8813 for (auto *E : Equiv) {
8814 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8815 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8816 << !M << (M ? M->getFullModuleName() : "");
8817 }
Richard Smith896c66e2015-10-21 07:13:52 +00008818}
8819
Mike Stump11289f42009-09-09 15:08:12 +00008820/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008821/// within an overload candidate set.
8822///
James Dennettffad8b72012-06-22 08:10:18 +00008823/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008824/// which overload resolution occurs.
8825///
James Dennettffad8b72012-06-22 08:10:18 +00008826/// \param Best If overload resolution was successful or found a deleted
8827/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008828///
8829/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008830OverloadingResult
8831OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008832 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008833 bool UserDefinedConversion) {
Artem Belevich18609102016-02-12 18:29:18 +00008834 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8835 std::transform(begin(), end(), std::back_inserter(Candidates),
8836 [](OverloadCandidate &Cand) { return &Cand; });
8837
Justin Lebar66a2ab92016-08-10 00:40:43 +00008838 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8839 // are accepted by both clang and NVCC. However, during a particular
Artem Belevich18609102016-02-12 18:29:18 +00008840 // compilation mode only one call variant is viable. We need to
8841 // exclude non-viable overload candidates from consideration based
8842 // only on their host/device attributes. Specifically, if one
8843 // candidate call is WrongSide and the other is SameSide, we ignore
8844 // the WrongSide candidate.
Justin Lebar25c4a812016-03-29 16:24:16 +00008845 if (S.getLangOpts().CUDA) {
Artem Belevich18609102016-02-12 18:29:18 +00008846 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8847 bool ContainsSameSideCandidate =
8848 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8849 return Cand->Function &&
8850 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8851 Sema::CFP_SameSide;
8852 });
8853 if (ContainsSameSideCandidate) {
8854 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8855 return Cand->Function &&
8856 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8857 Sema::CFP_WrongSide;
8858 };
8859 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8860 IsWrongSideCandidate),
8861 Candidates.end());
8862 }
8863 }
8864
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008865 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008866 Best = end();
Artem Belevich18609102016-02-12 18:29:18 +00008867 for (auto *Cand : Candidates)
John McCall5c32be02010-08-24 20:38:10 +00008868 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008869 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008870 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008871 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008872
8873 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008874 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008875 return OR_No_Viable_Function;
8876
Richard Smith2dbe4042015-11-04 19:26:32 +00008877 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
Richard Smith896c66e2015-10-21 07:13:52 +00008878
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008879 // Make sure that this function is better than every other viable
8880 // function. If not, we have an ambiguity.
Artem Belevich18609102016-02-12 18:29:18 +00008881 for (auto *Cand : Candidates) {
Mike Stump11289f42009-09-09 15:08:12 +00008882 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008883 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008884 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008885 UserDefinedConversion)) {
Richard Smith2dbe4042015-11-04 19:26:32 +00008886 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8887 Cand->Function)) {
8888 EquivalentCands.push_back(Cand->Function);
Richard Smith896c66e2015-10-21 07:13:52 +00008889 continue;
8890 }
8891
John McCall5c32be02010-08-24 20:38:10 +00008892 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008893 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008894 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008895 }
Mike Stump11289f42009-09-09 15:08:12 +00008896
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008897 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008898 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008899 (Best->Function->isDeleted() ||
8900 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008901 return OR_Deleted;
8902
Richard Smith2dbe4042015-11-04 19:26:32 +00008903 if (!EquivalentCands.empty())
8904 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8905 EquivalentCands);
Richard Smith896c66e2015-10-21 07:13:52 +00008906
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008907 return OR_Success;
8908}
8909
John McCall53262c92010-01-12 02:15:36 +00008910namespace {
8911
8912enum OverloadCandidateKind {
8913 oc_function,
8914 oc_method,
8915 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008916 oc_function_template,
8917 oc_method_template,
8918 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008919 oc_implicit_default_constructor,
8920 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008921 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008922 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008923 oc_implicit_move_assignment,
Richard Smith5179eb72016-06-28 19:03:57 +00008924 oc_inherited_constructor,
8925 oc_inherited_constructor_template
John McCall53262c92010-01-12 02:15:36 +00008926};
8927
John McCalle1ac8d12010-01-13 00:25:19 +00008928OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
Richard Smithc2bebe92016-05-11 20:37:46 +00008929 NamedDecl *Found,
John McCalle1ac8d12010-01-13 00:25:19 +00008930 FunctionDecl *Fn,
8931 std::string &Description) {
8932 bool isTemplate = false;
8933
8934 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8935 isTemplate = true;
8936 Description = S.getTemplateArgumentBindingsText(
8937 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8938 }
John McCallfd0b2f82010-01-06 09:43:14 +00008939
8940 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
Richard Smith5179eb72016-06-28 19:03:57 +00008941 if (!Ctor->isImplicit()) {
8942 if (isa<ConstructorUsingShadowDecl>(Found))
8943 return isTemplate ? oc_inherited_constructor_template
8944 : oc_inherited_constructor;
8945 else
8946 return isTemplate ? oc_constructor_template : oc_constructor;
8947 }
Sebastian Redl08905022011-02-05 19:23:19 +00008948
Alexis Hunt119c10e2011-05-25 23:16:36 +00008949 if (Ctor->isDefaultConstructor())
8950 return oc_implicit_default_constructor;
8951
8952 if (Ctor->isMoveConstructor())
8953 return oc_implicit_move_constructor;
8954
8955 assert(Ctor->isCopyConstructor() &&
8956 "unexpected sort of implicit constructor");
8957 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008958 }
8959
8960 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8961 // This actually gets spelled 'candidate function' for now, but
8962 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008963 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008964 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008965
Alexis Hunt119c10e2011-05-25 23:16:36 +00008966 if (Meth->isMoveAssignmentOperator())
8967 return oc_implicit_move_assignment;
8968
Douglas Gregor12695102012-02-10 08:36:38 +00008969 if (Meth->isCopyAssignmentOperator())
8970 return oc_implicit_copy_assignment;
8971
8972 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8973 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008974 }
8975
John McCalle1ac8d12010-01-13 00:25:19 +00008976 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008977}
8978
Richard Smith5179eb72016-06-28 19:03:57 +00008979void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
8980 // FIXME: It'd be nice to only emit a note once per using-decl per overload
8981 // set.
8982 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
8983 S.Diag(FoundDecl->getLocation(),
8984 diag::note_ovl_candidate_inherited_constructor)
8985 << Shadow->getNominatedBaseClass();
Sebastian Redl08905022011-02-05 19:23:19 +00008986}
8987
John McCall53262c92010-01-12 02:15:36 +00008988} // end anonymous namespace
8989
George Burgess IV5f21c712015-10-12 19:57:04 +00008990static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8991 const FunctionDecl *FD) {
8992 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8993 bool AlwaysTrue;
8994 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8995 return false;
8996 if (!AlwaysTrue)
8997 return false;
8998 }
8999 return true;
9000}
9001
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009002/// \brief Returns true if we can take the address of the function.
9003///
9004/// \param Complain - If true, we'll emit a diagnostic
9005/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9006/// we in overload resolution?
9007/// \param Loc - The location of the statement we're complaining about. Ignored
9008/// if we're not complaining, or if we're in overload resolution.
9009static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9010 bool Complain,
9011 bool InOverloadResolution,
9012 SourceLocation Loc) {
9013 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9014 if (Complain) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009015 if (InOverloadResolution)
9016 S.Diag(FD->getLocStart(),
9017 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9018 else
9019 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9020 }
9021 return false;
9022 }
9023
George Burgess IV21081362016-07-24 23:12:40 +00009024 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9025 return P->hasAttr<PassObjectSizeAttr>();
9026 });
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009027 if (I == FD->param_end())
9028 return true;
9029
9030 if (Complain) {
9031 // Add one to ParamNo because it's user-facing
9032 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9033 if (InOverloadResolution)
9034 S.Diag(FD->getLocation(),
9035 diag::note_ovl_candidate_has_pass_object_size_params)
9036 << ParamNo;
9037 else
9038 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9039 << FD << ParamNo;
9040 }
9041 return false;
9042}
9043
9044static bool checkAddressOfCandidateIsAvailable(Sema &S,
9045 const FunctionDecl *FD) {
9046 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9047 /*InOverloadResolution=*/true,
9048 /*Loc=*/SourceLocation());
9049}
9050
9051bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9052 bool Complain,
9053 SourceLocation Loc) {
9054 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9055 /*InOverloadResolution=*/false,
9056 Loc);
9057}
9058
John McCall53262c92010-01-12 02:15:36 +00009059// Notes the location of an overload candidate.
Richard Smithc2bebe92016-05-11 20:37:46 +00009060void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9061 QualType DestType, bool TakingAddress) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009062 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9063 return;
9064
John McCalle1ac8d12010-01-13 00:25:19 +00009065 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009066 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00009067 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9068 << (unsigned) K << FnDesc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009069
9070 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
Richard Trieucaff2472011-11-23 22:32:32 +00009071 Diag(Fn->getLocation(), PD);
Richard Smith5179eb72016-06-28 19:03:57 +00009072 MaybeEmitInheritedConstructorNote(*this, Found);
John McCallfd0b2f82010-01-06 09:43:14 +00009073}
9074
Nick Lewyckyed4265c2013-09-22 10:06:01 +00009075// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00009076// OverloadedExpr
George Burgess IV5f21c712015-10-12 19:57:04 +00009077void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9078 bool TakingAddress) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009079 assert(OverloadedExpr->getType() == Context.OverloadTy);
9080
9081 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9082 OverloadExpr *OvlExpr = Ovl.Expression;
9083
9084 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9085 IEnd = OvlExpr->decls_end();
9086 I != IEnd; ++I) {
9087 if (FunctionTemplateDecl *FunTmpl =
9088 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009089 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
George Burgess IV5f21c712015-10-12 19:57:04 +00009090 TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009091 } else if (FunctionDecl *Fun
9092 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009093 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009094 }
9095 }
9096}
9097
John McCall0d1da222010-01-12 00:44:57 +00009098/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9099/// "lead" diagnostic; it will be given two arguments, the source and
9100/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00009101void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9102 Sema &S,
9103 SourceLocation CaretLoc,
9104 const PartialDiagnostic &PDiag) const {
9105 S.Diag(CaretLoc, PDiag)
9106 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009107 // FIXME: The note limiting machinery is borrowed from
9108 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9109 // refactoring here.
9110 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9111 unsigned CandsShown = 0;
9112 AmbiguousConversionSequence::const_iterator I, E;
9113 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9114 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9115 break;
9116 ++CandsShown;
Richard Smithc2bebe92016-05-11 20:37:46 +00009117 S.NoteOverloadCandidate(I->first, I->second);
John McCall0d1da222010-01-12 00:44:57 +00009118 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00009119 if (I != E)
9120 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00009121}
9122
Richard Smith17c00b42014-11-12 01:24:00 +00009123static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009124 unsigned I, bool TakingCandidateAddress) {
John McCall6a61b522010-01-13 09:16:55 +00009125 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9126 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00009127 assert(Cand->Function && "for now, candidate must be a function");
9128 FunctionDecl *Fn = Cand->Function;
9129
9130 // There's a conversion slot for the object argument if this is a
9131 // non-constructor method. Note that 'I' corresponds the
9132 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00009133 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00009134 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00009135 if (I == 0)
9136 isObjectArgument = true;
9137 else
9138 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00009139 }
9140
John McCalle1ac8d12010-01-13 00:25:19 +00009141 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009142 OverloadCandidateKind FnKind =
9143 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCalle1ac8d12010-01-13 00:25:19 +00009144
John McCall6a61b522010-01-13 09:16:55 +00009145 Expr *FromExpr = Conv.Bad.FromExpr;
9146 QualType FromTy = Conv.Bad.getFromType();
9147 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00009148
John McCallfb7ad0f2010-02-02 02:42:52 +00009149 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00009150 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00009151 Expr *E = FromExpr->IgnoreParens();
9152 if (isa<UnaryOperator>(E))
9153 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00009154 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00009155
9156 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9157 << (unsigned) FnKind << FnDesc
9158 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9159 << ToTy << Name << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009160 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCallfb7ad0f2010-02-02 02:42:52 +00009161 return;
9162 }
9163
John McCall6d174642010-01-23 08:10:49 +00009164 // Do some hand-waving analysis to see if the non-viability is due
9165 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00009166 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9167 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9168 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9169 CToTy = RT->getPointeeType();
9170 else {
9171 // TODO: detect and diagnose the full richness of const mismatches.
9172 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
Richard Trieucc3949d2016-02-18 22:34:54 +00009173 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9174 CFromTy = FromPT->getPointeeType();
9175 CToTy = ToPT->getPointeeType();
9176 }
John McCall47000992010-01-14 03:28:57 +00009177 }
9178
9179 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9180 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00009181 Qualifiers FromQs = CFromTy.getQualifiers();
9182 Qualifiers ToQs = CToTy.getQualifiers();
9183
9184 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9185 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9186 << (unsigned) FnKind << FnDesc
9187 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9188 << FromTy
9189 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9190 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009191 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009192 return;
9193 }
9194
John McCall31168b02011-06-15 23:02:42 +00009195 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009196 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00009197 << (unsigned) FnKind << FnDesc
9198 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9199 << FromTy
9200 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9201 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009202 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall31168b02011-06-15 23:02:42 +00009203 return;
9204 }
9205
Douglas Gregoraec25842011-04-26 23:16:46 +00009206 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9207 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9208 << (unsigned) FnKind << FnDesc
9209 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9210 << FromTy
9211 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9212 << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009213 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregoraec25842011-04-26 23:16:46 +00009214 return;
9215 }
9216
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009217 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9218 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9219 << (unsigned) FnKind << FnDesc
9220 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9221 << FromTy << FromQs.hasUnaligned() << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009222 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Andrey Bokhanko45d41322016-05-11 18:38:21 +00009223 return;
9224 }
9225
John McCall47000992010-01-14 03:28:57 +00009226 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9227 assert(CVR && "unexpected qualifiers mismatch");
9228
9229 if (isObjectArgument) {
9230 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9231 << (unsigned) FnKind << FnDesc
9232 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9233 << FromTy << (CVR - 1);
9234 } else {
9235 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9236 << (unsigned) FnKind << FnDesc
9237 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9238 << FromTy << (CVR - 1) << I+1;
9239 }
Richard Smith5179eb72016-06-28 19:03:57 +00009240 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall47000992010-01-14 03:28:57 +00009241 return;
9242 }
9243
Sebastian Redla72462c2011-09-24 17:48:32 +00009244 // Special diagnostic for failure to convert an initializer list, since
9245 // telling the user that it has type void is not useful.
9246 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9247 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9248 << (unsigned) FnKind << FnDesc
9249 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9250 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009251 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Sebastian Redla72462c2011-09-24 17:48:32 +00009252 return;
9253 }
9254
John McCall6d174642010-01-23 08:10:49 +00009255 // Diagnose references or pointers to incomplete types differently,
9256 // since it's far from impossible that the incompleteness triggered
9257 // the failure.
9258 QualType TempFromTy = FromTy.getNonReferenceType();
9259 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9260 TempFromTy = PTy->getPointeeType();
9261 if (TempFromTy->isIncompleteType()) {
David Blaikieac928932016-03-04 22:29:11 +00009262 // Emit the generic diagnostic and, optionally, add the hints to it.
John McCall6d174642010-01-23 08:10:49 +00009263 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9264 << (unsigned) FnKind << FnDesc
9265 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
David Blaikieac928932016-03-04 22:29:11 +00009266 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9267 << (unsigned) (Cand->Fix.Kind);
9268
Richard Smith5179eb72016-06-28 19:03:57 +00009269 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6d174642010-01-23 08:10:49 +00009270 return;
9271 }
9272
Douglas Gregor56f2e342010-06-30 23:01:39 +00009273 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009274 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009275 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9276 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9277 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9278 FromPtrTy->getPointeeType()) &&
9279 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9280 !ToPtrTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009281 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00009282 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009283 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00009284 }
9285 } else if (const ObjCObjectPointerType *FromPtrTy
9286 = FromTy->getAs<ObjCObjectPointerType>()) {
9287 if (const ObjCObjectPointerType *ToPtrTy
9288 = ToTy->getAs<ObjCObjectPointerType>())
9289 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9290 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9291 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9292 FromPtrTy->getPointeeType()) &&
9293 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009294 BaseToDerivedConversion = 2;
9295 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009296 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9297 !FromTy->isIncompleteType() &&
9298 !ToRefTy->getPointeeType()->isIncompleteType() &&
Richard Smith0f59cb32015-12-18 21:45:41 +00009299 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009300 BaseToDerivedConversion = 3;
9301 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9302 ToTy.getNonReferenceType().getCanonicalType() ==
9303 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009304 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9305 << (unsigned) FnKind << FnDesc
9306 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9307 << (unsigned) isObjectArgument << I + 1;
Richard Smith5179eb72016-06-28 19:03:57 +00009308 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009309 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009310 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00009311 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009312
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009313 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009314 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009315 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00009316 << (unsigned) FnKind << FnDesc
9317 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00009318 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009319 << FromTy << ToTy << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009320 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Douglas Gregor56f2e342010-06-30 23:01:39 +00009321 return;
9322 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009323
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009324 if (isa<ObjCObjectPointerType>(CFromTy) &&
9325 isa<PointerType>(CToTy)) {
9326 Qualifiers FromQs = CFromTy.getQualifiers();
9327 Qualifiers ToQs = CToTy.getQualifiers();
9328 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9329 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9330 << (unsigned) FnKind << FnDesc
9331 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9332 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Richard Smith5179eb72016-06-28 19:03:57 +00009333 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00009334 return;
9335 }
9336 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009337
9338 if (TakingCandidateAddress &&
9339 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9340 return;
9341
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009342 // Emit the generic diagnostic and, optionally, add the hints to it.
9343 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9344 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00009345 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009346 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9347 << (unsigned) (Cand->Fix.Kind);
9348
9349 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00009350 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9351 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009352 FDiag << *HI;
9353 S.Diag(Fn->getLocation(), FDiag);
9354
Richard Smith5179eb72016-06-28 19:03:57 +00009355 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall6a61b522010-01-13 09:16:55 +00009356}
9357
Larisse Voufo98b20f12013-07-19 23:00:19 +00009358/// Additional arity mismatch diagnosis specific to a function overload
9359/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9360/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00009361static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9362 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00009363 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00009364 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009365
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009366 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00009367 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009368 // right number of arguments, because only overloaded operators have
9369 // the weird behavior of overloading member and non-member functions.
9370 // Just don't report anything.
9371 if (Fn->isInvalidDecl() &&
9372 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009373 return true;
9374
9375 if (NumArgs < MinParams) {
9376 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9377 (Cand->FailureKind == ovl_fail_bad_deduction &&
9378 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9379 } else {
9380 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9381 (Cand->FailureKind == ovl_fail_bad_deduction &&
9382 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9383 }
9384
9385 return false;
9386}
9387
9388/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smithc2bebe92016-05-11 20:37:46 +00009389static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9390 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009391 assert(isa<FunctionDecl>(D) &&
9392 "The templated declaration should at least be a function"
9393 " when diagnosing bad template argument deduction due to too many"
9394 " or too few arguments");
9395
9396 FunctionDecl *Fn = cast<FunctionDecl>(D);
9397
9398 // TODO: treat calls to a missing default constructor as a special case
9399 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9400 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00009401
John McCall6a61b522010-01-13 09:16:55 +00009402 // at least / at most / exactly
9403 unsigned mode, modeCount;
9404 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009405 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9406 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00009407 mode = 0; // "at least"
9408 else
9409 mode = 2; // "exactly"
9410 modeCount = MinParams;
9411 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00009412 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00009413 mode = 1; // "at most"
9414 else
9415 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00009416 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00009417 }
9418
9419 std::string Description;
Richard Smithc2bebe92016-05-11 20:37:46 +00009420 OverloadCandidateKind FnKind =
9421 ClassifyOverloadCandidate(S, Found, Fn, Description);
John McCall6a61b522010-01-13 09:16:55 +00009422
Richard Smith10ff50d2012-05-11 05:16:41 +00009423 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9424 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00009425 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9426 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00009427 else
9428 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00009429 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9430 << mode << modeCount << NumFormalArgs;
Richard Smith5179eb72016-06-28 19:03:57 +00009431 MaybeEmitInheritedConstructorNote(S, Found);
John McCalle1ac8d12010-01-13 00:25:19 +00009432}
9433
Larisse Voufo98b20f12013-07-19 23:00:19 +00009434/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00009435static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9436 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009437 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
Richard Smithc2bebe92016-05-11 20:37:46 +00009438 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009439}
Larisse Voufo47c08452013-07-19 22:53:23 +00009440
Richard Smith17c00b42014-11-12 01:24:00 +00009441static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00009442 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9443 return TD;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009444 llvm_unreachable("Unsupported: Getting the described template declaration"
9445 " for bad deduction diagnosis");
9446}
9447
9448/// Diagnose a failed template-argument deduction.
Richard Smithc2bebe92016-05-11 20:37:46 +00009449static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
Richard Smith17c00b42014-11-12 01:24:00 +00009450 DeductionFailureInfo &DeductionFailure,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009451 unsigned NumArgs,
9452 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009453 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009454 NamedDecl *ParamD;
9455 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9456 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9457 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009458 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009459 case Sema::TDK_Success:
9460 llvm_unreachable("TDK_success while diagnosing bad deduction");
9461
9462 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009463 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009464 S.Diag(Templated->getLocation(),
9465 diag::note_ovl_candidate_incomplete_deduction)
9466 << ParamD->getDeclName();
Richard Smith5179eb72016-06-28 19:03:57 +00009467 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009468 return;
9469 }
9470
John McCall42d7d192010-08-05 09:05:08 +00009471 case Sema::TDK_Underqualified: {
9472 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9473 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9474
Larisse Voufo98b20f12013-07-19 23:00:19 +00009475 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009476
9477 // Param will have been canonicalized, but it should just be a
9478 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009479 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009480 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009481 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009482 assert(S.Context.hasSameType(Param, NonCanonParam));
9483
9484 // Arg has also been canonicalized, but there's nothing we can do
9485 // about that. It also doesn't matter as much, because it won't
9486 // have any template parameters in it (because deduction isn't
9487 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009488 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009489
Larisse Voufo98b20f12013-07-19 23:00:19 +00009490 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9491 << ParamD->getDeclName() << Arg << NonCanonParam;
Richard Smith5179eb72016-06-28 19:03:57 +00009492 MaybeEmitInheritedConstructorNote(S, Found);
John McCall42d7d192010-08-05 09:05:08 +00009493 return;
9494 }
9495
9496 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009497 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009498 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009499 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009500 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009501 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009502 which = 1;
9503 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009504 which = 2;
9505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009506
Larisse Voufo98b20f12013-07-19 23:00:19 +00009507 S.Diag(Templated->getLocation(),
9508 diag::note_ovl_candidate_inconsistent_deduction)
9509 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9510 << *DeductionFailure.getSecondArg();
Richard Smith5179eb72016-06-28 19:03:57 +00009511 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009512 return;
9513 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009514
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009515 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009516 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009517 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009518 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009519 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009520 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009521 else {
9522 int index = 0;
9523 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9524 index = TTP->getIndex();
9525 else if (NonTypeTemplateParmDecl *NTTP
9526 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9527 index = NTTP->getIndex();
9528 else
9529 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009530 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009531 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009532 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009533 }
Richard Smith5179eb72016-06-28 19:03:57 +00009534 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009535 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009536
Douglas Gregor02eb4832010-05-08 18:13:28 +00009537 case Sema::TDK_TooManyArguments:
9538 case Sema::TDK_TooFewArguments:
Richard Smithc2bebe92016-05-11 20:37:46 +00009539 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009540 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009541
9542 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009543 S.Diag(Templated->getLocation(),
9544 diag::note_ovl_candidate_instantiation_depth);
Richard Smith5179eb72016-06-28 19:03:57 +00009545 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009546 return;
9547
9548 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009549 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009550 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009551 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009552 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009553 TemplateArgString = " ";
9554 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009555 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009556 }
9557
Richard Smith6f8d2c62012-05-09 05:17:00 +00009558 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009559 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009560 if (PDiag && PDiag->second.getDiagID() ==
9561 diag::err_typename_nested_not_found_enable_if) {
9562 // FIXME: Use the source range of the condition, and the fully-qualified
9563 // name of the enable_if template. These are both present in PDiag.
9564 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9565 << "'enable_if'" << TemplateArgString;
9566 return;
9567 }
9568
Richard Smith9ca64612012-05-07 09:03:25 +00009569 // Format the SFINAE diagnostic into the argument string.
9570 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9571 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009572 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009573 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009574 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009575 SFINAEArgString = ": ";
9576 R = SourceRange(PDiag->first, PDiag->first);
9577 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9578 }
9579
Larisse Voufo98b20f12013-07-19 23:00:19 +00009580 S.Diag(Templated->getLocation(),
9581 diag::note_ovl_candidate_substitution_failure)
9582 << TemplateArgString << SFINAEArgString << R;
Richard Smith5179eb72016-06-28 19:03:57 +00009583 MaybeEmitInheritedConstructorNote(S, Found);
Douglas Gregord09efd42010-05-08 20:07:26 +00009584 return;
9585 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009586
Richard Smith8c6eeb92013-01-31 04:03:12 +00009587 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009588 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9589 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009590 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009591 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009592 return;
9593 }
9594
Richard Smith9b534542015-12-31 02:02:54 +00009595 case Sema::TDK_DeducedMismatch: {
9596 // Format the template argument list into the argument string.
9597 SmallString<128> TemplateArgString;
9598 if (TemplateArgumentList *Args =
9599 DeductionFailure.getTemplateArgumentList()) {
9600 TemplateArgString = " ";
9601 TemplateArgString += S.getTemplateArgumentBindingsText(
9602 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9603 }
9604
9605 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9606 << (*DeductionFailure.getCallArgIndex() + 1)
9607 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9608 << TemplateArgString;
9609 break;
9610 }
9611
Richard Trieue3732352013-04-08 21:11:40 +00009612 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009613 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009614 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9615 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009616 if (FirstTA.getKind() == TemplateArgument::Template &&
9617 SecondTA.getKind() == TemplateArgument::Template) {
9618 TemplateName FirstTN = FirstTA.getAsTemplate();
9619 TemplateName SecondTN = SecondTA.getAsTemplate();
9620 if (FirstTN.getKind() == TemplateName::Template &&
9621 SecondTN.getKind() == TemplateName::Template) {
9622 if (FirstTN.getAsTemplateDecl()->getName() ==
9623 SecondTN.getAsTemplateDecl()->getName()) {
9624 // FIXME: This fixes a bad diagnostic where both templates are named
9625 // the same. This particular case is a bit difficult since:
9626 // 1) It is passed as a string to the diagnostic printer.
9627 // 2) The diagnostic printer only attempts to find a better
9628 // name for types, not decls.
9629 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009630 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009631 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9632 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9633 return;
9634 }
9635 }
9636 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009637
9638 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9639 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9640 return;
9641
Faisal Vali2b391ab2013-09-26 19:54:12 +00009642 // FIXME: For generic lambda parameters, check if the function is a lambda
9643 // call operator, and if so, emit a prettier and more informative
9644 // diagnostic that mentions 'auto' and lambda in addition to
9645 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009646 S.Diag(Templated->getLocation(),
9647 diag::note_ovl_candidate_non_deduced_mismatch)
9648 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009649 return;
Richard Trieue3732352013-04-08 21:11:40 +00009650 }
John McCall8b9ed552010-02-01 18:53:26 +00009651 // TODO: diagnose these individually, then kill off
9652 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009653 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009654 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
Richard Smith5179eb72016-06-28 19:03:57 +00009655 MaybeEmitInheritedConstructorNote(S, Found);
John McCall8b9ed552010-02-01 18:53:26 +00009656 return;
9657 }
9658}
9659
Larisse Voufo98b20f12013-07-19 23:00:19 +00009660/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009661static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009662 unsigned NumArgs,
9663 bool TakingCandidateAddress) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009664 unsigned TDK = Cand->DeductionFailure.Result;
9665 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9666 if (CheckArityMismatch(S, Cand, NumArgs))
9667 return;
9668 }
Richard Smithc2bebe92016-05-11 20:37:46 +00009669 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009670 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009671}
9672
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009673/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009674static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009675 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9676 FunctionDecl *Callee = Cand->Function;
9677
9678 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9679 CalleeTarget = S.IdentifyCUDATarget(Callee);
9680
9681 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009682 OverloadCandidateKind FnKind =
9683 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009684
9685 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009686 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9687
9688 // This could be an implicit constructor for which we could not infer the
9689 // target due to a collsion. Diagnose that case.
9690 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9691 if (Meth != nullptr && Meth->isImplicit()) {
9692 CXXRecordDecl *ParentClass = Meth->getParent();
9693 Sema::CXXSpecialMember CSM;
9694
9695 switch (FnKind) {
9696 default:
9697 return;
9698 case oc_implicit_default_constructor:
9699 CSM = Sema::CXXDefaultConstructor;
9700 break;
9701 case oc_implicit_copy_constructor:
9702 CSM = Sema::CXXCopyConstructor;
9703 break;
9704 case oc_implicit_move_constructor:
9705 CSM = Sema::CXXMoveConstructor;
9706 break;
9707 case oc_implicit_copy_assignment:
9708 CSM = Sema::CXXCopyAssignment;
9709 break;
9710 case oc_implicit_move_assignment:
9711 CSM = Sema::CXXMoveAssignment;
9712 break;
9713 };
9714
9715 bool ConstRHS = false;
9716 if (Meth->getNumParams()) {
9717 if (const ReferenceType *RT =
9718 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9719 ConstRHS = RT->getPointeeType().isConstQualified();
9720 }
9721 }
9722
9723 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9724 /* ConstRHS */ ConstRHS,
9725 /* Diagnose */ true);
9726 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009727}
9728
Richard Smith17c00b42014-11-12 01:24:00 +00009729static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009730 FunctionDecl *Callee = Cand->Function;
9731 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9732
9733 S.Diag(Callee->getLocation(),
9734 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9735 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9736}
9737
John McCall8b9ed552010-02-01 18:53:26 +00009738/// Generates a 'note' diagnostic for an overload candidate. We've
9739/// already generated a primary error at the call site.
9740///
9741/// It really does need to be a single diagnostic with its caret
9742/// pointed at the candidate declaration. Yes, this creates some
9743/// major challenges of technical writing. Yes, this makes pointing
9744/// out problems with specific arguments quite awkward. It's still
9745/// better than generating twenty screens of text for every failed
9746/// overload.
9747///
9748/// It would be great to be able to express per-candidate problems
9749/// more richly for those diagnostic clients that cared, but we'd
9750/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009751static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009752 unsigned NumArgs,
9753 bool TakingCandidateAddress) {
John McCall53262c92010-01-12 02:15:36 +00009754 FunctionDecl *Fn = Cand->Function;
9755
John McCall12f97bc2010-01-08 04:41:39 +00009756 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009757 if (Cand->Viable && (Fn->isDeleted() ||
9758 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009759 std::string FnDesc;
Richard Smithc2bebe92016-05-11 20:37:46 +00009760 OverloadCandidateKind FnKind =
9761 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009762
9763 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009764 << FnKind << FnDesc
9765 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009766 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCalld3224162010-01-08 00:58:21 +00009767 return;
John McCall12f97bc2010-01-08 04:41:39 +00009768 }
9769
John McCalle1ac8d12010-01-13 00:25:19 +00009770 // We don't really have anything else to say about viable candidates.
9771 if (Cand->Viable) {
Richard Smithc2bebe92016-05-11 20:37:46 +00009772 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009773 return;
9774 }
John McCall0d1da222010-01-12 00:44:57 +00009775
John McCall6a61b522010-01-13 09:16:55 +00009776 switch (Cand->FailureKind) {
9777 case ovl_fail_too_many_arguments:
9778 case ovl_fail_too_few_arguments:
9779 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009780
John McCall6a61b522010-01-13 09:16:55 +00009781 case ovl_fail_bad_deduction:
Richard Smithc2bebe92016-05-11 20:37:46 +00009782 return DiagnoseBadDeduction(S, Cand, NumArgs,
9783 TakingCandidateAddress);
John McCall8b9ed552010-02-01 18:53:26 +00009784
John McCall578a1f82014-12-14 01:46:53 +00009785 case ovl_fail_illegal_constructor: {
9786 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9787 << (Fn->getPrimaryTemplate() ? 1 : 0);
Richard Smith5179eb72016-06-28 19:03:57 +00009788 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
John McCall578a1f82014-12-14 01:46:53 +00009789 return;
9790 }
9791
John McCallfe796dd2010-01-23 05:17:32 +00009792 case ovl_fail_trivial_conversion:
9793 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009794 case ovl_fail_final_conversion_not_exact:
Richard Smithc2bebe92016-05-11 20:37:46 +00009795 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009796
John McCall65eb8792010-02-25 01:37:24 +00009797 case ovl_fail_bad_conversion: {
9798 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009799 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009800 if (Cand->Conversions[I].isBad())
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009801 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009802
John McCall6a61b522010-01-13 09:16:55 +00009803 // FIXME: this currently happens when we're called from SemaInit
9804 // when user-conversion overload fails. Figure out how to handle
9805 // those conditions and diagnose them well.
Richard Smithc2bebe92016-05-11 20:37:46 +00009806 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009807 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009808
9809 case ovl_fail_bad_target:
9810 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009811
9812 case ovl_fail_enable_if:
9813 return DiagnoseFailedEnableIfAttr(S, Cand);
George Burgess IV7204ed92016-01-07 02:26:57 +00009814
9815 case ovl_fail_addr_not_available: {
9816 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9817 (void)Available;
9818 assert(!Available);
9819 break;
9820 }
John McCall65eb8792010-02-25 01:37:24 +00009821 }
John McCalld3224162010-01-08 00:58:21 +00009822}
9823
Richard Smith17c00b42014-11-12 01:24:00 +00009824static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009825 // Desugar the type of the surrogate down to a function type,
9826 // retaining as many typedefs as possible while still showing
9827 // the function type (and, therefore, its parameter types).
9828 QualType FnType = Cand->Surrogate->getConversionType();
9829 bool isLValueReference = false;
9830 bool isRValueReference = false;
9831 bool isPointer = false;
9832 if (const LValueReferenceType *FnTypeRef =
9833 FnType->getAs<LValueReferenceType>()) {
9834 FnType = FnTypeRef->getPointeeType();
9835 isLValueReference = true;
9836 } else if (const RValueReferenceType *FnTypeRef =
9837 FnType->getAs<RValueReferenceType>()) {
9838 FnType = FnTypeRef->getPointeeType();
9839 isRValueReference = true;
9840 }
9841 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9842 FnType = FnTypePtr->getPointeeType();
9843 isPointer = true;
9844 }
9845 // Desugar down to a function type.
9846 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9847 // Reconstruct the pointer/reference as appropriate.
9848 if (isPointer) FnType = S.Context.getPointerType(FnType);
9849 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9850 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9851
9852 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9853 << FnType;
9854}
9855
Richard Smith17c00b42014-11-12 01:24:00 +00009856static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9857 SourceLocation OpLoc,
9858 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009859 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009860 std::string TypeStr("operator");
9861 TypeStr += Opc;
9862 TypeStr += "(";
9863 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009864 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009865 TypeStr += ")";
9866 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9867 } else {
9868 TypeStr += ", ";
9869 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9870 TypeStr += ")";
9871 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9872 }
9873}
9874
Richard Smith17c00b42014-11-12 01:24:00 +00009875static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9876 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009877 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009878 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9879 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009880 if (ICS.isBad()) break; // all meaningless after first invalid
9881 if (!ICS.isAmbiguous()) continue;
9882
Richard Smithc2bebe92016-05-11 20:37:46 +00009883 ICS.DiagnoseAmbiguousConversion(
9884 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009885 }
9886}
9887
Larisse Voufo98b20f12013-07-19 23:00:19 +00009888static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009889 if (Cand->Function)
9890 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009891 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009892 return Cand->Surrogate->getLocation();
9893 return SourceLocation();
9894}
9895
Larisse Voufo98b20f12013-07-19 23:00:19 +00009896static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009897 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009898 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009899 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009900
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009901 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009902 case Sema::TDK_Incomplete:
9903 return 1;
9904
9905 case Sema::TDK_Underqualified:
9906 case Sema::TDK_Inconsistent:
9907 return 2;
9908
9909 case Sema::TDK_SubstitutionFailure:
Richard Smith9b534542015-12-31 02:02:54 +00009910 case Sema::TDK_DeducedMismatch:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009911 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009912 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009913 return 3;
9914
9915 case Sema::TDK_InstantiationDepth:
9916 case Sema::TDK_FailedOverloadResolution:
9917 return 4;
9918
9919 case Sema::TDK_InvalidExplicitArguments:
9920 return 5;
9921
9922 case Sema::TDK_TooManyArguments:
9923 case Sema::TDK_TooFewArguments:
9924 return 6;
9925 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009926 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009927}
9928
Richard Smith17c00b42014-11-12 01:24:00 +00009929namespace {
John McCallad2587a2010-01-12 00:48:53 +00009930struct CompareOverloadCandidatesForDisplay {
9931 Sema &S;
Richard Smith0f59cb32015-12-18 21:45:41 +00009932 SourceLocation Loc;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009933 size_t NumArgs;
9934
Richard Smith0f59cb32015-12-18 21:45:41 +00009935 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009936 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009937
9938 bool operator()(const OverloadCandidate *L,
9939 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009940 // Fast-path this check.
9941 if (L == R) return false;
9942
John McCall12f97bc2010-01-08 04:41:39 +00009943 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009944 if (L->Viable) {
9945 if (!R->Viable) return true;
9946
9947 // TODO: introduce a tri-valued comparison for overload
9948 // candidates. Would be more worthwhile if we had a sort
9949 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009950 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9951 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009952 } else if (R->Viable)
9953 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009954
John McCall3712d9e2010-01-15 23:32:50 +00009955 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009956
John McCall3712d9e2010-01-15 23:32:50 +00009957 // Criteria by which we can sort non-viable candidates:
9958 if (!L->Viable) {
9959 // 1. Arity mismatches come after other candidates.
9960 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009961 L->FailureKind == ovl_fail_too_few_arguments) {
9962 if (R->FailureKind == ovl_fail_too_many_arguments ||
9963 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009964 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9965 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9966 if (LDist == RDist) {
9967 if (L->FailureKind == R->FailureKind)
9968 // Sort non-surrogates before surrogates.
9969 return !L->IsSurrogate && R->IsSurrogate;
9970 // Sort candidates requiring fewer parameters than there were
9971 // arguments given after candidates requiring more parameters
9972 // than there were arguments given.
9973 return L->FailureKind == ovl_fail_too_many_arguments;
9974 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009975 return LDist < RDist;
9976 }
John McCall3712d9e2010-01-15 23:32:50 +00009977 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009978 }
John McCall3712d9e2010-01-15 23:32:50 +00009979 if (R->FailureKind == ovl_fail_too_many_arguments ||
9980 R->FailureKind == ovl_fail_too_few_arguments)
9981 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009982
John McCallfe796dd2010-01-23 05:17:32 +00009983 // 2. Bad conversions come first and are ordered by the number
9984 // of bad conversions and quality of good conversions.
9985 if (L->FailureKind == ovl_fail_bad_conversion) {
9986 if (R->FailureKind != ovl_fail_bad_conversion)
9987 return true;
9988
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009989 // The conversion that can be fixed with a smaller number of changes,
9990 // comes first.
9991 unsigned numLFixes = L->Fix.NumConversionsFixed;
9992 unsigned numRFixes = R->Fix.NumConversionsFixed;
9993 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9994 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009995 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009996 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009997 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009998
John McCallfe796dd2010-01-23 05:17:32 +00009999 // If there's any ordering between the defined conversions...
10000 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +000010001 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +000010002
10003 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +000010004 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +000010005 for (unsigned E = L->NumConversions; I != E; ++I) {
Richard Smith0f59cb32015-12-18 21:45:41 +000010006 switch (CompareImplicitConversionSequences(S, Loc,
John McCall5c32be02010-08-24 20:38:10 +000010007 L->Conversions[I],
10008 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +000010009 case ImplicitConversionSequence::Better:
10010 leftBetter++;
10011 break;
10012
10013 case ImplicitConversionSequence::Worse:
10014 leftBetter--;
10015 break;
10016
10017 case ImplicitConversionSequence::Indistinguishable:
10018 break;
10019 }
10020 }
10021 if (leftBetter > 0) return true;
10022 if (leftBetter < 0) return false;
10023
10024 } else if (R->FailureKind == ovl_fail_bad_conversion)
10025 return false;
10026
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010027 if (L->FailureKind == ovl_fail_bad_deduction) {
10028 if (R->FailureKind != ovl_fail_bad_deduction)
10029 return true;
10030
10031 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10032 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +000010033 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +000010034 } else if (R->FailureKind == ovl_fail_bad_deduction)
10035 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +000010036
John McCall3712d9e2010-01-15 23:32:50 +000010037 // TODO: others?
10038 }
10039
10040 // Sort everything else by location.
10041 SourceLocation LLoc = GetLocationForCandidate(L);
10042 SourceLocation RLoc = GetLocationForCandidate(R);
10043
10044 // Put candidates without locations (e.g. builtins) at the end.
10045 if (LLoc.isInvalid()) return false;
10046 if (RLoc.isInvalid()) return true;
10047
10048 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +000010049 }
10050};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010051}
John McCall12f97bc2010-01-08 04:41:39 +000010052
John McCallfe796dd2010-01-23 05:17:32 +000010053/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010054/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +000010055static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10056 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +000010057 assert(!Cand->Viable);
10058
10059 // Don't do anything on failures other than bad conversion.
10060 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10061
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010062 // We only want the FixIts if all the arguments can be corrected.
10063 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +000010064 // Use a implicit copy initialization to check conversion fixes.
10065 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010066
John McCallfe796dd2010-01-23 05:17:32 +000010067 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +000010068 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +000010069 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +000010070 while (true) {
10071 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10072 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010073 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +000010074 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +000010075 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010076 }
John McCallfe796dd2010-01-23 05:17:32 +000010077 }
10078
10079 if (ConvIdx == ConvCount)
10080 return;
10081
John McCall65eb8792010-02-25 01:37:24 +000010082 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10083 "remaining conversion is initialized?");
10084
Douglas Gregoradc7a702010-04-16 17:45:54 +000010085 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +000010086 // operation somehow.
10087 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +000010088
10089 const FunctionProtoType* Proto;
10090 unsigned ArgIdx = ConvIdx;
10091
10092 if (Cand->IsSurrogate) {
10093 QualType ConvType
10094 = Cand->Surrogate->getConversionType().getNonReferenceType();
10095 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10096 ConvType = ConvPtrType->getPointeeType();
10097 Proto = ConvType->getAs<FunctionProtoType>();
10098 ArgIdx--;
10099 } else if (Cand->Function) {
10100 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10101 if (isa<CXXMethodDecl>(Cand->Function) &&
10102 !isa<CXXConstructorDecl>(Cand->Function))
10103 ArgIdx--;
10104 } else {
10105 // Builtin binary operator with a bad first conversion.
10106 assert(ConvCount <= 3);
10107 for (; ConvIdx != ConvCount; ++ConvIdx)
10108 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +000010109 = TryCopyInitialization(S, Args[ConvIdx],
10110 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010111 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +000010112 /*InOverloadResolution*/ true,
10113 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +000010114 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +000010115 return;
10116 }
10117
10118 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010119 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +000010120 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010121 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +000010122 Cand->Conversions[ConvIdx] = TryCopyInitialization(
10123 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10124 /*InOverloadResolution=*/true,
10125 /*AllowObjCWritebackConversion=*/
10126 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010127 // Store the FixIt in the candidate if it exists.
10128 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +000010129 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +000010130 }
John McCallfe796dd2010-01-23 05:17:32 +000010131 else
10132 Cand->Conversions[ConvIdx].setEllipsis();
10133 }
10134}
10135
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010136/// PrintOverloadCandidates - When overload resolution fails, prints
10137/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +000010138/// set.
John McCall5c32be02010-08-24 20:38:10 +000010139void OverloadCandidateSet::NoteCandidates(Sema &S,
10140 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010141 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +000010142 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +000010143 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +000010144 // Sort the candidates by viability and position. Sorting directly would
10145 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010146 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +000010147 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10148 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +000010149 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +000010150 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +000010151 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010152 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010153 if (Cand->Function || Cand->IsSurrogate)
10154 Cands.push_back(Cand);
10155 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10156 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +000010157 }
10158 }
10159
John McCallad2587a2010-01-12 00:48:53 +000010160 std::sort(Cands.begin(), Cands.end(),
Richard Smith0f59cb32015-12-18 21:45:41 +000010161 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010162
John McCall0d1da222010-01-12 00:44:57 +000010163 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +000010164
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010165 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +000010166 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010167 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +000010168 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10169 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +000010170
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010171 // Set an arbitrary limit on the number of candidate functions we'll spam
10172 // the user with. FIXME: This limit should depend on details of the
10173 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +000010174 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010175 break;
10176 }
10177 ++CandsShown;
10178
John McCalld3224162010-01-08 00:58:21 +000010179 if (Cand->Function)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010180 NoteFunctionCandidate(S, Cand, Args.size(),
10181 /*TakingCandidateAddress=*/false);
John McCalld3224162010-01-08 00:58:21 +000010182 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +000010183 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010184 else {
10185 assert(Cand->Viable &&
10186 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +000010187 // Generally we only see ambiguities including viable builtin
10188 // operators if overload resolution got screwed up by an
10189 // ambiguous user-defined conversion.
10190 //
10191 // FIXME: It's quite possible for different conversions to see
10192 // different ambiguities, though.
10193 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +000010194 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +000010195 ReportedAmbiguousConversions = true;
10196 }
John McCalld3224162010-01-08 00:58:21 +000010197
John McCall0d1da222010-01-12 00:44:57 +000010198 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +000010199 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +000010200 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010201 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +000010202
10203 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +000010204 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010205}
10206
Larisse Voufo98b20f12013-07-19 23:00:19 +000010207static SourceLocation
10208GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10209 return Cand->Specialization ? Cand->Specialization->getLocation()
10210 : SourceLocation();
10211}
10212
Richard Smith17c00b42014-11-12 01:24:00 +000010213namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010214struct CompareTemplateSpecCandidatesForDisplay {
10215 Sema &S;
10216 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10217
10218 bool operator()(const TemplateSpecCandidate *L,
10219 const TemplateSpecCandidate *R) {
10220 // Fast-path this check.
10221 if (L == R)
10222 return false;
10223
10224 // Assuming that both candidates are not matches...
10225
10226 // Sort by the ranking of deduction failures.
10227 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10228 return RankDeductionFailure(L->DeductionFailure) <
10229 RankDeductionFailure(R->DeductionFailure);
10230
10231 // Sort everything else by location.
10232 SourceLocation LLoc = GetLocationForCandidate(L);
10233 SourceLocation RLoc = GetLocationForCandidate(R);
10234
10235 // Put candidates without locations (e.g. builtins) at the end.
10236 if (LLoc.isInvalid())
10237 return false;
10238 if (RLoc.isInvalid())
10239 return true;
10240
10241 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10242 }
10243};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010244}
Larisse Voufo98b20f12013-07-19 23:00:19 +000010245
10246/// Diagnose a template argument deduction failure.
10247/// We are treating these failures as overload failures due to bad
10248/// deductions.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010249void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10250 bool ForTakingAddress) {
Richard Smithc2bebe92016-05-11 20:37:46 +000010251 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010252 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010253}
10254
10255void TemplateSpecCandidateSet::destroyCandidates() {
10256 for (iterator i = begin(), e = end(); i != e; ++i) {
10257 i->DeductionFailure.Destroy();
10258 }
10259}
10260
10261void TemplateSpecCandidateSet::clear() {
10262 destroyCandidates();
10263 Candidates.clear();
10264}
10265
10266/// NoteCandidates - When no template specialization match is found, prints
10267/// diagnostic messages containing the non-matching specializations that form
10268/// the candidate set.
10269/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10270/// OCD == OCD_AllCandidates and Cand->Viable == false.
10271void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10272 // Sort the candidates by position (assuming no candidate is a match).
10273 // Sorting directly would be prohibitive, so we make a set of pointers
10274 // and sort those.
10275 SmallVector<TemplateSpecCandidate *, 32> Cands;
10276 Cands.reserve(size());
10277 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10278 if (Cand->Specialization)
10279 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +000010280 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010281 // in general, want to list every possible builtin candidate.
10282 }
10283
10284 std::sort(Cands.begin(), Cands.end(),
10285 CompareTemplateSpecCandidatesForDisplay(S));
10286
10287 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10288 // for generalization purposes (?).
10289 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10290
10291 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10292 unsigned CandsShown = 0;
10293 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10294 TemplateSpecCandidate *Cand = *I;
10295
10296 // Set an arbitrary limit on the number of candidates we'll spam
10297 // the user with. FIXME: This limit should depend on details of the
10298 // candidate list.
10299 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10300 break;
10301 ++CandsShown;
10302
10303 assert(Cand->Specialization &&
10304 "Non-matching built-in candidates are not added to Cands.");
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010305 Cand->NoteDeductionFailure(S, ForTakingAddress);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010306 }
10307
10308 if (I != E)
10309 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10310}
10311
Douglas Gregorb491ed32011-02-19 21:32:49 +000010312// [PossiblyAFunctionType] --> [Return]
10313// NonFunctionType --> NonFunctionType
10314// R (A) --> R(A)
10315// R (*)(A) --> R (A)
10316// R (&)(A) --> R (A)
10317// R (S::*)(A) --> R (A)
10318QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10319 QualType Ret = PossiblyAFunctionType;
10320 if (const PointerType *ToTypePtr =
10321 PossiblyAFunctionType->getAs<PointerType>())
10322 Ret = ToTypePtr->getPointeeType();
10323 else if (const ReferenceType *ToTypeRef =
10324 PossiblyAFunctionType->getAs<ReferenceType>())
10325 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010326 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +000010327 PossiblyAFunctionType->getAs<MemberPointerType>())
10328 Ret = MemTypePtr->getPointeeType();
10329 Ret =
10330 Context.getCanonicalType(Ret).getUnqualifiedType();
10331 return Ret;
10332}
Douglas Gregorcd695e52008-11-10 20:40:00 +000010333
Richard Smith17c00b42014-11-12 01:24:00 +000010334namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010335// A helper class to help with address of function resolution
10336// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +000010337class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010338 Sema& S;
10339 Expr* SourceExpr;
10340 const QualType& TargetType;
10341 QualType TargetFunctionType; // Extracted function type from target type
10342
10343 bool Complain;
10344 //DeclAccessPair& ResultFunctionAccessPair;
10345 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010346
Douglas Gregorb491ed32011-02-19 21:32:49 +000010347 bool TargetTypeIsNonStaticMemberFunction;
10348 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +000010349 bool StaticMemberFunctionFromBoundPointer;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010350 bool HasComplained;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010351
Douglas Gregorb491ed32011-02-19 21:32:49 +000010352 OverloadExpr::FindResult OvlExprInfo;
10353 OverloadExpr *OvlExpr;
10354 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010355 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010356 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010357
Douglas Gregorb491ed32011-02-19 21:32:49 +000010358public:
Larisse Voufo98b20f12013-07-19 23:00:19 +000010359 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10360 const QualType &TargetType, bool Complain)
10361 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10362 Complain(Complain), Context(S.getASTContext()),
10363 TargetTypeIsNonStaticMemberFunction(
10364 !!TargetType->getAs<MemberPointerType>()),
10365 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +000010366 StaticMemberFunctionFromBoundPointer(false),
George Burgess IV5f2ef452015-10-12 18:40:58 +000010367 HasComplained(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010368 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10369 OvlExpr(OvlExprInfo.Expression),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010370 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010371 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +000010372
David Majnemera4f7c7a2013-08-01 06:13:59 +000010373 if (TargetFunctionType->isFunctionType()) {
10374 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10375 if (!UME->isImplicitAccess() &&
10376 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10377 StaticMemberFunctionFromBoundPointer = true;
10378 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10379 DeclAccessPair dap;
10380 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10381 OvlExpr, false, &dap)) {
10382 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10383 if (!Method->isStatic()) {
10384 // If the target type is a non-function type and the function found
10385 // is a non-static member function, pretend as if that was the
10386 // target, it's the only possible type to end up with.
10387 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +000010388
David Majnemera4f7c7a2013-08-01 06:13:59 +000010389 // And skip adding the function if its not in the proper form.
10390 // We'll diagnose this due to an empty set of functions.
10391 if (!OvlExprInfo.HasFormOfMemberPointer)
10392 return;
Chandler Carruthffce2452011-03-29 08:08:18 +000010393 }
10394
David Majnemera4f7c7a2013-08-01 06:13:59 +000010395 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +000010396 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010397 return;
Douglas Gregor9b146582009-07-08 20:55:45 +000010398 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010399
10400 if (OvlExpr->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +000010401 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +000010402
Douglas Gregorb491ed32011-02-19 21:32:49 +000010403 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10404 // C++ [over.over]p4:
10405 // If more than one function is selected, [...]
George Burgess IV2a6150d2015-10-16 01:17:38 +000010406 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010407 if (FoundNonTemplateFunction)
10408 EliminateAllTemplateMatches();
10409 else
10410 EliminateAllExceptMostSpecializedTemplate();
10411 }
10412 }
Artem Belevich94a55e82015-09-22 17:22:59 +000010413
Justin Lebar25c4a812016-03-29 16:24:16 +000010414 if (S.getLangOpts().CUDA && Matches.size() > 1)
Artem Belevich94a55e82015-09-22 17:22:59 +000010415 EliminateSuboptimalCudaMatches();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010416 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010417
10418 bool hasComplained() const { return HasComplained; }
10419
Douglas Gregorb491ed32011-02-19 21:32:49 +000010420private:
George Burgess IV6da4c202016-03-23 02:33:58 +000010421 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10422 QualType Discard;
10423 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10424 S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard);
George Burgess IV2a6150d2015-10-16 01:17:38 +000010425 }
10426
George Burgess IV6da4c202016-03-23 02:33:58 +000010427 /// \return true if A is considered a better overload candidate for the
10428 /// desired type than B.
10429 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10430 // If A doesn't have exactly the correct type, we don't want to classify it
10431 // as "better" than anything else. This way, the user is required to
10432 // disambiguate for us if there are multiple candidates and no exact match.
10433 return candidateHasExactlyCorrectType(A) &&
10434 (!candidateHasExactlyCorrectType(B) ||
George Burgess IV3dc166912016-05-10 01:59:34 +000010435 compareEnableIfAttrs(S, A, B) == Comparison::Better);
George Burgess IV6da4c202016-03-23 02:33:58 +000010436 }
10437
10438 /// \return true if we were able to eliminate all but one overload candidate,
10439 /// false otherwise.
George Burgess IV2a6150d2015-10-16 01:17:38 +000010440 bool eliminiateSuboptimalOverloadCandidates() {
10441 // Same algorithm as overload resolution -- one pass to pick the "best",
10442 // another pass to be sure that nothing is better than the best.
10443 auto Best = Matches.begin();
10444 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10445 if (isBetterCandidate(I->second, Best->second))
10446 Best = I;
10447
10448 const FunctionDecl *BestFn = Best->second;
10449 auto IsBestOrInferiorToBest = [this, BestFn](
10450 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10451 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10452 };
10453
10454 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10455 // option, so we can potentially give the user a better error
10456 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10457 return false;
10458 Matches[0] = *Best;
10459 Matches.resize(1);
10460 return true;
10461 }
10462
Douglas Gregorb491ed32011-02-19 21:32:49 +000010463 bool isTargetTypeAFunction() const {
10464 return TargetFunctionType->isFunctionType();
10465 }
10466
10467 // [ToType] [Return]
10468
10469 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10470 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10471 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10472 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10473 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10474 }
10475
10476 // return true if any matching specializations were found
10477 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10478 const DeclAccessPair& CurAccessFunPair) {
10479 if (CXXMethodDecl *Method
10480 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10481 // Skip non-static function templates when converting to pointer, and
10482 // static when converting to member pointer.
10483 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10484 return false;
10485 }
10486 else if (TargetTypeIsNonStaticMemberFunction)
10487 return false;
10488
10489 // C++ [over.over]p2:
10490 // If the name is a function template, template argument deduction is
10491 // done (14.8.2.2), and if the argument deduction succeeds, the
10492 // resulting template argument list is used to generate a single
10493 // function template specialization, which is added to the set of
10494 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010495 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010496 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +000010497 if (Sema::TemplateDeductionResult Result
10498 = S.DeduceTemplateArguments(FunctionTemplate,
10499 &OvlExplicitTemplateArgs,
10500 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010501 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010502 // Make a note of the failed deduction for diagnostics.
10503 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010504 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010505 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +000010506 return false;
10507 }
10508
Douglas Gregor19a41f12013-04-17 08:45:07 +000010509 // Template argument deduction ensures that we have an exact match or
10510 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010511 // This function template specicalization works.
Douglas Gregor19a41f12013-04-17 08:45:07 +000010512 assert(S.isSameOrCompatibleFunctionType(
10513 Context.getCanonicalType(Specialization->getType()),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010514 Context.getCanonicalType(TargetFunctionType)));
George Burgess IV5f21c712015-10-12 19:57:04 +000010515
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010516 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
George Burgess IV5f21c712015-10-12 19:57:04 +000010517 return false;
10518
Douglas Gregorb491ed32011-02-19 21:32:49 +000010519 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10520 return true;
10521 }
10522
10523 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10524 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010525 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010526 // Skip non-static functions when converting to pointer, and static
10527 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010528 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10529 return false;
10530 }
10531 else if (TargetTypeIsNonStaticMemberFunction)
10532 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010533
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010534 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010535 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010536 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Justin Lebarb0080032016-08-10 01:09:11 +000010537 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010538 return false;
10539
Richard Smith2a7d4812013-05-04 07:00:32 +000010540 // If any candidate has a placeholder return type, trigger its deduction
10541 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010542 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010543 FunDecl->getReturnType()->isUndeducedType() &&
George Burgess IV5f2ef452015-10-12 18:40:58 +000010544 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10545 HasComplained |= Complain;
Richard Smith2a7d4812013-05-04 07:00:32 +000010546 return false;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010547 }
Richard Smith2a7d4812013-05-04 07:00:32 +000010548
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010549 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
George Burgess IV5f21c712015-10-12 19:57:04 +000010550 return false;
10551
George Burgess IV6da4c202016-03-23 02:33:58 +000010552 // If we're in C, we need to support types that aren't exactly identical.
10553 if (!S.getLangOpts().CPlusPlus ||
10554 candidateHasExactlyCorrectType(FunDecl)) {
George Burgess IV5f21c712015-10-12 19:57:04 +000010555 Matches.push_back(std::make_pair(
10556 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010557 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010558 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010559 }
Mike Stump11289f42009-09-09 15:08:12 +000010560 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010561
10562 return false;
10563 }
10564
10565 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10566 bool Ret = false;
10567
10568 // If the overload expression doesn't have the form of a pointer to
10569 // member, don't try to convert it to a pointer-to-member type.
10570 if (IsInvalidFormOfPointerToMemberFunction())
10571 return false;
10572
10573 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10574 E = OvlExpr->decls_end();
10575 I != E; ++I) {
10576 // Look through any using declarations to find the underlying function.
10577 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10578
10579 // C++ [over.over]p3:
10580 // Non-member functions and static member functions match
10581 // targets of type "pointer-to-function" or "reference-to-function."
10582 // Nonstatic member functions match targets of
10583 // type "pointer-to-member-function."
10584 // Note that according to DR 247, the containing class does not matter.
10585 if (FunctionTemplateDecl *FunctionTemplate
10586 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10587 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10588 Ret = true;
10589 }
10590 // If we have explicit template arguments supplied, skip non-templates.
10591 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10592 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10593 Ret = true;
10594 }
10595 assert(Ret || Matches.empty());
10596 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010597 }
10598
Douglas Gregorb491ed32011-02-19 21:32:49 +000010599 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010600 // [...] and any given function template specialization F1 is
10601 // eliminated if the set contains a second function template
10602 // specialization whose function template is more specialized
10603 // than the function template of F1 according to the partial
10604 // ordering rules of 14.5.5.2.
10605
10606 // The algorithm specified above is quadratic. We instead use a
10607 // two-pass algorithm (similar to the one used to identify the
10608 // best viable function in an overload set) that identifies the
10609 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010610
10611 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10612 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10613 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010614
Larisse Voufo98b20f12013-07-19 23:00:19 +000010615 // TODO: It looks like FailedCandidates does not serve much purpose
10616 // here, since the no_viable diagnostic has index 0.
10617 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010618 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010619 SourceExpr->getLocStart(), S.PDiag(),
Richard Smith5179eb72016-06-28 19:03:57 +000010620 S.PDiag(diag::err_addr_ovl_ambiguous)
10621 << Matches[0].second->getDeclName(),
10622 S.PDiag(diag::note_ovl_candidate)
10623 << (unsigned)oc_function_template,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010624 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010625
Douglas Gregorb491ed32011-02-19 21:32:49 +000010626 if (Result != MatchesCopy.end()) {
10627 // Make it the first and only element
10628 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10629 Matches[0].second = cast<FunctionDecl>(*Result);
10630 Matches.resize(1);
George Burgess IV5f2ef452015-10-12 18:40:58 +000010631 } else
10632 HasComplained |= Complain;
John McCall58cc69d2010-01-27 01:50:18 +000010633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010634
Douglas Gregorb491ed32011-02-19 21:32:49 +000010635 void EliminateAllTemplateMatches() {
10636 // [...] any function template specializations in the set are
10637 // eliminated if the set also contains a non-template function, [...]
10638 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010639 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010640 ++I;
10641 else {
10642 Matches[I] = Matches[--N];
Artem Belevich94a55e82015-09-22 17:22:59 +000010643 Matches.resize(N);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010644 }
10645 }
10646 }
10647
Artem Belevich94a55e82015-09-22 17:22:59 +000010648 void EliminateSuboptimalCudaMatches() {
10649 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10650 }
10651
Douglas Gregorb491ed32011-02-19 21:32:49 +000010652public:
10653 void ComplainNoMatchesFound() const {
10654 assert(Matches.empty());
10655 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10656 << OvlExpr->getName() << TargetFunctionType
10657 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010658 if (FailedCandidates.empty())
George Burgess IV5f21c712015-10-12 19:57:04 +000010659 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10660 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010661 else {
10662 // We have some deduction failure messages. Use them to diagnose
10663 // the function templates, and diagnose the non-template candidates
10664 // normally.
10665 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10666 IEnd = OvlExpr->decls_end();
10667 I != IEnd; ++I)
10668 if (FunctionDecl *Fun =
10669 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010670 if (!functionHasPassObjectSizeParams(Fun))
Richard Smithc2bebe92016-05-11 20:37:46 +000010671 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010672 /*TakingAddress=*/true);
Richard Smith0d905472013-08-14 00:00:44 +000010673 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10674 }
10675 }
10676
Douglas Gregorb491ed32011-02-19 21:32:49 +000010677 bool IsInvalidFormOfPointerToMemberFunction() const {
10678 return TargetTypeIsNonStaticMemberFunction &&
10679 !OvlExprInfo.HasFormOfMemberPointer;
10680 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010681
Douglas Gregorb491ed32011-02-19 21:32:49 +000010682 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10683 // TODO: Should we condition this on whether any functions might
10684 // have matched, or is it more appropriate to do that in callers?
10685 // TODO: a fixit wouldn't hurt.
10686 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10687 << TargetType << OvlExpr->getSourceRange();
10688 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010689
10690 bool IsStaticMemberFunctionFromBoundPointer() const {
10691 return StaticMemberFunctionFromBoundPointer;
10692 }
10693
10694 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10695 S.Diag(OvlExpr->getLocStart(),
10696 diag::err_invalid_form_pointer_member_function)
10697 << OvlExpr->getSourceRange();
10698 }
10699
Douglas Gregorb491ed32011-02-19 21:32:49 +000010700 void ComplainOfInvalidConversion() const {
10701 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10702 << OvlExpr->getName() << TargetType;
10703 }
10704
10705 void ComplainMultipleMatchesFound() const {
10706 assert(Matches.size() > 1);
10707 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10708 << OvlExpr->getName()
10709 << OvlExpr->getSourceRange();
George Burgess IV5f21c712015-10-12 19:57:04 +000010710 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10711 /*TakingAddress=*/true);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010712 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010713
10714 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10715
Douglas Gregorb491ed32011-02-19 21:32:49 +000010716 int getNumMatches() const { return Matches.size(); }
10717
10718 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010719 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010720 return Matches[0].second;
10721 }
10722
10723 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010724 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010725 return &Matches[0].first;
10726 }
10727};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010728}
Richard Smith17c00b42014-11-12 01:24:00 +000010729
Douglas Gregorb491ed32011-02-19 21:32:49 +000010730/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10731/// an overloaded function (C++ [over.over]), where @p From is an
10732/// expression with overloaded function type and @p ToType is the type
10733/// we're trying to resolve to. For example:
10734///
10735/// @code
10736/// int f(double);
10737/// int f(int);
10738///
10739/// int (*pfd)(double) = f; // selects f(double)
10740/// @endcode
10741///
10742/// This routine returns the resulting FunctionDecl if it could be
10743/// resolved, and NULL otherwise. When @p Complain is true, this
10744/// routine will emit diagnostics if there is an error.
10745FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010746Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10747 QualType TargetType,
10748 bool Complain,
10749 DeclAccessPair &FoundResult,
10750 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010751 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010752
10753 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10754 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010755 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010756 FunctionDecl *Fn = nullptr;
George Burgess IV5f2ef452015-10-12 18:40:58 +000010757 bool ShouldComplain = Complain && !Resolver.hasComplained();
10758 if (NumMatches == 0 && ShouldComplain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010759 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10760 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10761 else
10762 Resolver.ComplainNoMatchesFound();
10763 }
George Burgess IV5f2ef452015-10-12 18:40:58 +000010764 else if (NumMatches > 1 && ShouldComplain)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010765 Resolver.ComplainMultipleMatchesFound();
10766 else if (NumMatches == 1) {
10767 Fn = Resolver.getMatchingFunctionDecl();
10768 assert(Fn);
10769 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010770 if (Complain) {
10771 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10772 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10773 else
10774 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10775 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010776 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010777
10778 if (pHadMultipleCandidates)
10779 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010780 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010781}
10782
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010783/// \brief Given an expression that refers to an overloaded function, try to
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010784/// resolve that function to a single function that can have its address taken.
10785/// This will modify `Pair` iff it returns non-null.
10786///
10787/// This routine can only realistically succeed if all but one candidates in the
10788/// overload set for SrcExpr cannot have their addresses taken.
10789FunctionDecl *
10790Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10791 DeclAccessPair &Pair) {
10792 OverloadExpr::FindResult R = OverloadExpr::find(E);
10793 OverloadExpr *Ovl = R.Expression;
10794 FunctionDecl *Result = nullptr;
10795 DeclAccessPair DAP;
10796 // Don't use the AddressOfResolver because we're specifically looking for
10797 // cases where we have one overload candidate that lacks
10798 // enable_if/pass_object_size/...
10799 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10800 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10801 if (!FD)
10802 return nullptr;
10803
10804 if (!checkAddressOfFunctionIsAvailable(FD))
10805 continue;
10806
10807 // We have more than one result; quit.
10808 if (Result)
10809 return nullptr;
10810 DAP = I.getPair();
10811 Result = FD;
10812 }
10813
10814 if (Result)
10815 Pair = DAP;
10816 return Result;
10817}
10818
George Burgess IVbeca4a32016-06-08 00:34:22 +000010819/// \brief Given an overloaded function, tries to turn it into a non-overloaded
10820/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10821/// will perform access checks, diagnose the use of the resultant decl, and, if
10822/// necessary, perform a function-to-pointer decay.
10823///
10824/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10825/// Otherwise, returns true. This may emit diagnostics and return true.
10826bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10827 ExprResult &SrcExpr) {
10828 Expr *E = SrcExpr.get();
10829 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10830
10831 DeclAccessPair DAP;
10832 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10833 if (!Found)
10834 return false;
10835
10836 // Emitting multiple diagnostics for a function that is both inaccessible and
10837 // unavailable is consistent with our behavior elsewhere. So, always check
10838 // for both.
10839 DiagnoseUseOfDecl(Found, E->getExprLoc());
10840 CheckAddressOfMemberAccess(E, DAP);
10841 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10842 if (Fixed->getType()->isFunctionType())
10843 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10844 else
10845 SrcExpr = Fixed;
10846 return true;
10847}
10848
George Burgess IV3cde9bf2016-03-19 21:36:10 +000010849/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010850/// resolve that overloaded function expression down to a single function.
10851///
10852/// This routine can only resolve template-ids that refer to a single function
10853/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010854/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010855/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010856///
10857/// If no template-ids are found, no diagnostics are emitted and NULL is
10858/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010859FunctionDecl *
10860Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10861 bool Complain,
10862 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010863 // C++ [over.over]p1:
10864 // [...] [Note: any redundant set of parentheses surrounding the
10865 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010866 // C++ [over.over]p1:
10867 // [...] The overloaded function name can be preceded by the &
10868 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010869
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010870 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010871 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010872 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010873
10874 TemplateArgumentListInfo ExplicitTemplateArgs;
James Y Knight04ec5bf2015-12-24 02:59:37 +000010875 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010876 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010877
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010878 // Look through all of the overloaded functions, searching for one
10879 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010880 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010881 for (UnresolvedSetIterator I = ovl->decls_begin(),
10882 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010883 // C++0x [temp.arg.explicit]p3:
10884 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010885 // where deduction is not done, if a template argument list is
10886 // specified and it, along with any default template arguments,
10887 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010888 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010889 FunctionTemplateDecl *FunctionTemplate
10890 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010891
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010892 // C++ [over.over]p2:
10893 // If the name is a function template, template argument deduction is
10894 // done (14.8.2.2), and if the argument deduction succeeds, the
10895 // resulting template argument list is used to generate a single
10896 // function template specialization, which is added to the set of
10897 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010898 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010899 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010900 if (TemplateDeductionResult Result
10901 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010902 Specialization, Info,
10903 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010904 // Make a note of the failed deduction for diagnostics.
10905 // TODO: Actually use the failed-deduction info?
10906 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +000010907 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +000010908 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010909 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010910 }
10911
John McCall0009fcc2011-04-26 20:42:42 +000010912 assert(Specialization && "no specialization and no error?");
10913
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010914 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010915 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010916 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010917 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10918 << ovl->getName();
10919 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010920 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010921 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010922 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010923
John McCall0009fcc2011-04-26 20:42:42 +000010924 Matched = Specialization;
10925 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010927
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010928 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010929 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010930 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010931 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010932
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010933 return Matched;
10934}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010935
Douglas Gregor1beec452011-03-12 01:48:56 +000010936
10937
10938
John McCall50a2c2c2011-10-11 23:14:30 +000010939// Resolve and fix an overloaded expression that can be resolved
10940// because it identifies a single function template specialization.
10941//
Douglas Gregor1beec452011-03-12 01:48:56 +000010942// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010943//
10944// Return true if it was logically possible to so resolve the
10945// expression, regardless of whether or not it succeeded. Always
10946// returns true if 'complain' is set.
10947bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10948 ExprResult &SrcExpr, bool doFunctionPointerConverion,
Craig Toppere335f252015-10-04 04:53:55 +000010949 bool complain, SourceRange OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010950 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010951 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010952 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010953
John McCall50a2c2c2011-10-11 23:14:30 +000010954 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010955
John McCall0009fcc2011-04-26 20:42:42 +000010956 DeclAccessPair found;
10957 ExprResult SingleFunctionExpression;
10958 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10959 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010960 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010961 SrcExpr = ExprError();
10962 return true;
10963 }
John McCall0009fcc2011-04-26 20:42:42 +000010964
10965 // It is only correct to resolve to an instance method if we're
10966 // resolving a form that's permitted to be a pointer to member.
10967 // Otherwise we'll end up making a bound member expression, which
10968 // is illegal in all the contexts we resolve like this.
10969 if (!ovl.HasFormOfMemberPointer &&
10970 isa<CXXMethodDecl>(fn) &&
10971 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010972 if (!complain) return false;
10973
10974 Diag(ovl.Expression->getExprLoc(),
10975 diag::err_bound_member_function)
10976 << 0 << ovl.Expression->getSourceRange();
10977
10978 // TODO: I believe we only end up here if there's a mix of
10979 // static and non-static candidates (otherwise the expression
10980 // would have 'bound member' type, not 'overload' type).
10981 // Ideally we would note which candidate was chosen and why
10982 // the static candidates were rejected.
10983 SrcExpr = ExprError();
10984 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010985 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010986
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010987 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010988 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010989 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010990
10991 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010992 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010993 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010994 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010995 if (SingleFunctionExpression.isInvalid()) {
10996 SrcExpr = ExprError();
10997 return true;
10998 }
10999 }
John McCall0009fcc2011-04-26 20:42:42 +000011000 }
11001
11002 if (!SingleFunctionExpression.isUsable()) {
11003 if (complain) {
11004 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11005 << ovl.Expression->getName()
11006 << DestTypeForComplaining
11007 << OpRangeForComplaining
11008 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000011009 NoteAllOverloadCandidates(SrcExpr.get());
11010
11011 SrcExpr = ExprError();
11012 return true;
11013 }
11014
11015 return false;
John McCall0009fcc2011-04-26 20:42:42 +000011016 }
11017
John McCall50a2c2c2011-10-11 23:14:30 +000011018 SrcExpr = SingleFunctionExpression;
11019 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000011020}
11021
Douglas Gregorcabea402009-09-22 15:41:20 +000011022/// \brief Add a single candidate to the overload set.
11023static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000011024 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000011025 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011026 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011027 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000011028 bool PartialOverloading,
11029 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000011030 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000011031 if (isa<UsingShadowDecl>(Callee))
11032 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11033
Douglas Gregorcabea402009-09-22 15:41:20 +000011034 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000011035 if (ExplicitTemplateArgs) {
11036 assert(!KnownValid && "Explicit template arguments?");
11037 return;
11038 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011039 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11040 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011041 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011042 return;
John McCalld14a8642009-11-21 08:51:07 +000011043 }
11044
11045 if (FunctionTemplateDecl *FuncTemplate
11046 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000011047 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011048 ExplicitTemplateArgs, Args, CandidateSet,
11049 /*SuppressUsedConversions=*/false,
11050 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000011051 return;
11052 }
11053
Richard Smith95ce4f62011-06-26 22:19:54 +000011054 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000011055}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011056
Douglas Gregorcabea402009-09-22 15:41:20 +000011057/// \brief Add the overload candidates named by callee and/or found by argument
11058/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000011059void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011060 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000011061 OverloadCandidateSet &CandidateSet,
11062 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000011063
11064#ifndef NDEBUG
11065 // Verify that ArgumentDependentLookup is consistent with the rules
11066 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000011067 //
Douglas Gregorcabea402009-09-22 15:41:20 +000011068 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11069 // and let Y be the lookup set produced by argument dependent
11070 // lookup (defined as follows). If X contains
11071 //
11072 // -- a declaration of a class member, or
11073 //
11074 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000011075 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000011076 //
11077 // -- a declaration that is neither a function or a function
11078 // template
11079 //
11080 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000011081
John McCall57500772009-12-16 12:17:52 +000011082 if (ULE->requiresADL()) {
11083 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11084 E = ULE->decls_end(); I != E; ++I) {
11085 assert(!(*I)->getDeclContext()->isRecord());
11086 assert(isa<UsingShadowDecl>(*I) ||
11087 !(*I)->getDeclContext()->isFunctionOrMethod());
11088 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000011089 }
11090 }
11091#endif
11092
John McCall57500772009-12-16 12:17:52 +000011093 // It would be nice to avoid this copy.
11094 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011095 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011096 if (ULE->hasExplicitTemplateArgs()) {
11097 ULE->copyTemplateArgumentsInto(TABuffer);
11098 ExplicitTemplateArgs = &TABuffer;
11099 }
11100
11101 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11102 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011103 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11104 CandidateSet, PartialOverloading,
11105 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000011106
John McCall57500772009-12-16 12:17:52 +000011107 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000011108 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011109 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000011110 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000011111}
John McCalld681c392009-12-16 08:11:27 +000011112
Richard Smith0603bbb2013-06-12 22:56:54 +000011113/// Determine whether a declaration with the specified name could be moved into
11114/// a different namespace.
11115static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11116 switch (Name.getCXXOverloadedOperator()) {
11117 case OO_New: case OO_Array_New:
11118 case OO_Delete: case OO_Array_Delete:
11119 return false;
11120
11121 default:
11122 return true;
11123 }
11124}
11125
Richard Smith998a5912011-06-05 22:42:48 +000011126/// Attempt to recover from an ill-formed use of a non-dependent name in a
11127/// template, where the non-dependent name was declared after the template
11128/// was defined. This is common in code written for a compilers which do not
11129/// correctly implement two-stage name lookup.
11130///
11131/// Returns true if a viable candidate was found and a diagnostic was issued.
11132static bool
11133DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11134 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000011135 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000011136 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000011137 ArrayRef<Expr *> Args,
11138 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000011139 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11140 return false;
11141
11142 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000011143 if (DC->isTransparentContext())
11144 continue;
11145
Richard Smith998a5912011-06-05 22:42:48 +000011146 SemaRef.LookupQualifiedName(R, DC);
11147
11148 if (!R.empty()) {
11149 R.suppressDiagnostics();
11150
11151 if (isa<CXXRecordDecl>(DC)) {
11152 // Don't diagnose names we find in classes; we get much better
11153 // diagnostics for these from DiagnoseEmptyLookup.
11154 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000011155 if (DoDiagnoseEmptyLookup)
11156 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000011157 return false;
11158 }
11159
Richard Smith100b24a2014-04-17 01:52:14 +000011160 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000011161 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11162 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011163 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000011164 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000011165
11166 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000011167 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000011168 // No viable functions. Don't bother the user with notes for functions
11169 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000011170 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000011171 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000011172 }
Richard Smith998a5912011-06-05 22:42:48 +000011173
11174 // Find the namespaces where ADL would have looked, and suggest
11175 // declaring the function there instead.
11176 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11177 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000011178 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000011179 AssociatedNamespaces,
11180 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000011181 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000011182 if (canBeDeclaredInNamespace(R.getLookupName())) {
11183 DeclContext *Std = SemaRef.getStdNamespace();
11184 for (Sema::AssociatedNamespaceSet::iterator
11185 it = AssociatedNamespaces.begin(),
11186 end = AssociatedNamespaces.end(); it != end; ++it) {
11187 // Never suggest declaring a function within namespace 'std'.
11188 if (Std && Std->Encloses(*it))
11189 continue;
Richard Smith21bae432012-12-22 02:46:14 +000011190
Richard Smith0603bbb2013-06-12 22:56:54 +000011191 // Never suggest declaring a function within a namespace with a
11192 // reserved name, like __gnu_cxx.
11193 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11194 if (NS &&
11195 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11196 continue;
11197
11198 SuggestedNamespaces.insert(*it);
11199 }
Richard Smith998a5912011-06-05 22:42:48 +000011200 }
11201
11202 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11203 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000011204 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000011205 SemaRef.Diag(Best->Function->getLocation(),
11206 diag::note_not_found_by_two_phase_lookup)
11207 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000011208 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000011209 SemaRef.Diag(Best->Function->getLocation(),
11210 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000011211 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000011212 } else {
11213 // FIXME: It would be useful to list the associated namespaces here,
11214 // but the diagnostics infrastructure doesn't provide a way to produce
11215 // a localized representation of a list of items.
11216 SemaRef.Diag(Best->Function->getLocation(),
11217 diag::note_not_found_by_two_phase_lookup)
11218 << R.getLookupName() << 2;
11219 }
11220
11221 // Try to recover by calling this function.
11222 return true;
11223 }
11224
11225 R.clear();
11226 }
11227
11228 return false;
11229}
11230
11231/// Attempt to recover from ill-formed use of a non-dependent operator in a
11232/// template, where the non-dependent operator was declared after the template
11233/// was defined.
11234///
11235/// Returns true if a viable candidate was found and a diagnostic was issued.
11236static bool
11237DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11238 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011239 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000011240 DeclarationName OpName =
11241 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11242 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11243 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000011244 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000011245 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000011246}
11247
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011248namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000011249class BuildRecoveryCallExprRAII {
11250 Sema &SemaRef;
11251public:
11252 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11253 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11254 SemaRef.IsBuildingRecoveryCallExpr = true;
11255 }
11256
11257 ~BuildRecoveryCallExprRAII() {
11258 SemaRef.IsBuildingRecoveryCallExpr = false;
11259 }
11260};
11261
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011262}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000011263
Kaelyn Takata89c881b2014-10-27 18:07:29 +000011264static std::unique_ptr<CorrectionCandidateCallback>
11265MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11266 bool HasTemplateArgs, bool AllowTypoCorrection) {
11267 if (!AllowTypoCorrection)
11268 return llvm::make_unique<NoTypoCorrectionCCC>();
11269 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11270 HasTemplateArgs, ME);
11271}
11272
John McCalld681c392009-12-16 08:11:27 +000011273/// Attempts to recover from a call where no functions were found.
11274///
11275/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000011276static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000011277BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000011278 UnresolvedLookupExpr *ULE,
11279 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000011280 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000011281 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011282 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000011283 // Do not try to recover if it is already building a recovery call.
11284 // This stops infinite loops for template instantiations like
11285 //
11286 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11287 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11288 //
11289 if (SemaRef.IsBuildingRecoveryCallExpr)
11290 return ExprError();
11291 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000011292
11293 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000011294 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000011295 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000011296
John McCall57500772009-12-16 12:17:52 +000011297 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000011298 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000011299 if (ULE->hasExplicitTemplateArgs()) {
11300 ULE->copyTemplateArgumentsInto(TABuffer);
11301 ExplicitTemplateArgs = &TABuffer;
11302 }
11303
John McCalld681c392009-12-16 08:11:27 +000011304 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11305 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000011306 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000011307 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000011308 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000011309 ExplicitTemplateArgs, Args,
11310 &DoDiagnoseEmptyLookup) &&
11311 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11312 S, SS, R,
11313 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11314 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11315 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000011316 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000011317
John McCall57500772009-12-16 12:17:52 +000011318 assert(!R.empty() && "lookup results empty despite recovery");
11319
11320 // Build an implicit member call if appropriate. Just drop the
11321 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000011322 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000011323 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011324 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11325 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011326 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000011327 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000011328 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000011329 else
11330 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11331
11332 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011333 return ExprError();
John McCall57500772009-12-16 12:17:52 +000011334
11335 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000011336 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000011337 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011338 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011339 MultiExprArg(Args.data(), Args.size()),
11340 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000011341}
Douglas Gregor4038cf42010-06-08 17:35:15 +000011342
Sam Panzer0f384432012-08-21 00:52:01 +000011343/// \brief Constructs and populates an OverloadedCandidateSet from
11344/// the given function.
11345/// \returns true when an the ExprResult output parameter has been set.
11346bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11347 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011348 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011349 SourceLocation RParenLoc,
11350 OverloadCandidateSet *CandidateSet,
11351 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000011352#ifndef NDEBUG
11353 if (ULE->requiresADL()) {
11354 // To do ADL, we must have found an unqualified name.
11355 assert(!ULE->getQualifier() && "qualified name with ADL");
11356
11357 // We don't perform ADL for implicit declarations of builtins.
11358 // Verify that this was correctly set up.
11359 FunctionDecl *F;
11360 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11361 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11362 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000011363 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011364
John McCall57500772009-12-16 12:17:52 +000011365 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011366 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000011367 }
John McCall57500772009-12-16 12:17:52 +000011368#endif
11369
John McCall4124c492011-10-17 18:40:02 +000011370 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011371 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000011372 *Result = ExprError();
11373 return true;
11374 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000011375
John McCall57500772009-12-16 12:17:52 +000011376 // Add the functions denoted by the callee to the set of candidate
11377 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011378 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000011379
Hans Wennborgb2747382015-06-12 21:23:23 +000011380 if (getLangOpts().MSVCCompat &&
11381 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000011382 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11383
11384 OverloadCandidateSet::iterator Best;
11385 if (CandidateSet->empty() ||
11386 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11387 OR_No_Viable_Function) {
11388 // In Microsoft mode, if we are inside a template class member function then
11389 // create a type dependent CallExpr. The goal is to postpone name lookup
11390 // to instantiation time to be able to search into type dependent base
11391 // classes.
11392 CallExpr *CE = new (Context) CallExpr(
11393 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011394 CE->setTypeDependent(true);
Richard Smithed9b8f02015-09-23 21:30:47 +000011395 CE->setValueDependent(true);
11396 CE->setInstantiationDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011397 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000011398 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000011399 }
Francois Pichetbcf64712011-09-07 00:14:57 +000011400 }
John McCalld681c392009-12-16 08:11:27 +000011401
Hans Wennborg64937c62015-06-11 21:21:57 +000011402 if (CandidateSet->empty())
11403 return false;
11404
John McCall4124c492011-10-17 18:40:02 +000011405 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000011406 return false;
11407}
John McCall4124c492011-10-17 18:40:02 +000011408
Sam Panzer0f384432012-08-21 00:52:01 +000011409/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11410/// the completed call expression. If overload resolution fails, emits
11411/// diagnostics and returns ExprError()
11412static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11413 UnresolvedLookupExpr *ULE,
11414 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011415 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011416 SourceLocation RParenLoc,
11417 Expr *ExecConfig,
11418 OverloadCandidateSet *CandidateSet,
11419 OverloadCandidateSet::iterator *Best,
11420 OverloadingResult OverloadResult,
11421 bool AllowTypoCorrection) {
11422 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011423 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011424 RParenLoc, /*EmptyLookup=*/true,
11425 AllowTypoCorrection);
11426
11427 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000011428 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000011429 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000011430 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011431 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11432 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000011433 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011434 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11435 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000011436 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011437
Richard Smith998a5912011-06-05 22:42:48 +000011438 case OR_No_Viable_Function: {
11439 // Try to recover by looking for viable functions which the user might
11440 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000011441 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011442 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000011443 /*EmptyLookup=*/false,
11444 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000011445 if (!Recovery.isInvalid())
11446 return Recovery;
11447
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011448 // If the user passes in a function that we can't take the address of, we
11449 // generally end up emitting really bad error messages. Here, we attempt to
11450 // emit better ones.
11451 for (const Expr *Arg : Args) {
11452 if (!Arg->getType()->isFunctionType())
11453 continue;
11454 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11455 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11456 if (FD &&
11457 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11458 Arg->getExprLoc()))
11459 return ExprError();
11460 }
11461 }
11462
11463 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11464 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011465 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011466 break;
Richard Smith998a5912011-06-05 22:42:48 +000011467 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011468
11469 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000011470 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000011471 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011472 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011473 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011474
Sam Panzer0f384432012-08-21 00:52:01 +000011475 case OR_Deleted: {
11476 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11477 << (*Best)->Function->isDeleted()
11478 << ULE->getName()
11479 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11480 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011481 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000011482
Sam Panzer0f384432012-08-21 00:52:01 +000011483 // We emitted an error for the unvailable/deleted function call but keep
11484 // the call in the AST.
11485 FunctionDecl *FDecl = (*Best)->Function;
11486 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011487 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11488 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000011489 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011490 }
11491
Douglas Gregorb412e172010-07-25 18:17:45 +000011492 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000011493 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000011494}
11495
George Burgess IV7204ed92016-01-07 02:26:57 +000011496static void markUnaddressableCandidatesUnviable(Sema &S,
11497 OverloadCandidateSet &CS) {
11498 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11499 if (I->Viable &&
11500 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11501 I->Viable = false;
11502 I->FailureKind = ovl_fail_addr_not_available;
11503 }
11504 }
11505}
11506
Sam Panzer0f384432012-08-21 00:52:01 +000011507/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11508/// (which eventually refers to the declaration Func) and the call
11509/// arguments Args/NumArgs, attempt to resolve the function call down
11510/// to a specific function. If overload resolution succeeds, returns
11511/// the call expression produced by overload resolution.
11512/// Otherwise, emits diagnostics and returns ExprError.
11513ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11514 UnresolvedLookupExpr *ULE,
11515 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011516 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011517 SourceLocation RParenLoc,
11518 Expr *ExecConfig,
George Burgess IV7204ed92016-01-07 02:26:57 +000011519 bool AllowTypoCorrection,
11520 bool CalleesAddressIsTaken) {
Richard Smith100b24a2014-04-17 01:52:14 +000011521 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11522 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000011523 ExprResult result;
11524
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011525 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11526 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000011527 return result;
11528
George Burgess IV7204ed92016-01-07 02:26:57 +000011529 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11530 // functions that aren't addressible are considered unviable.
11531 if (CalleesAddressIsTaken)
11532 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11533
Sam Panzer0f384432012-08-21 00:52:01 +000011534 OverloadCandidateSet::iterator Best;
11535 OverloadingResult OverloadResult =
11536 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11537
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011538 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000011539 RParenLoc, ExecConfig, &CandidateSet,
11540 &Best, OverloadResult,
11541 AllowTypoCorrection);
11542}
11543
John McCall4c4c1df2010-01-26 03:27:55 +000011544static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000011545 return Functions.size() > 1 ||
11546 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11547}
11548
Douglas Gregor084d8552009-03-13 23:49:33 +000011549/// \brief Create a unary operation that may resolve to an overloaded
11550/// operator.
11551///
11552/// \param OpLoc The location of the operator itself (e.g., '*').
11553///
Craig Toppera92ffb02015-12-10 08:51:49 +000011554/// \param Opc The UnaryOperatorKind that describes this operator.
Douglas Gregor084d8552009-03-13 23:49:33 +000011555///
James Dennett18348b62012-06-22 08:52:37 +000011556/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000011557/// considered by overload resolution. The caller needs to build this
11558/// set based on the context using, e.g.,
11559/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11560/// set should not contain any member functions; those will be added
11561/// by CreateOverloadedUnaryOp().
11562///
James Dennett91738ff2012-06-22 10:32:46 +000011563/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000011564ExprResult
Craig Toppera92ffb02015-12-10 08:51:49 +000011565Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011566 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000011567 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011568 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11569 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11570 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011571 // TODO: provide better source location info.
11572 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000011573
John McCall4124c492011-10-17 18:40:02 +000011574 if (checkPlaceholderForOverload(*this, Input))
11575 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011576
Craig Topperc3ec1492014-05-26 06:22:03 +000011577 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000011578 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000011579
Douglas Gregor084d8552009-03-13 23:49:33 +000011580 // For post-increment and post-decrement, add the implicit '0' as
11581 // the second argument, so that we know this is a post-increment or
11582 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000011583 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011584 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011585 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11586 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000011587 NumArgs = 2;
11588 }
11589
Richard Smithe54c3072013-05-05 15:51:06 +000011590 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11591
Douglas Gregor084d8552009-03-13 23:49:33 +000011592 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000011593 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011594 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11595 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011596
Craig Topperc3ec1492014-05-26 06:22:03 +000011597 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000011598 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011599 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011600 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011601 /*ADL*/ true, IsOverloaded(Fns),
11602 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011603 return new (Context)
11604 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11605 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000011606 }
11607
11608 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011609 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000011610
11611 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011612 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011613
11614 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011615 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011616
John McCall4c4c1df2010-01-26 03:27:55 +000011617 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000011618 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000011619 /*ExplicitTemplateArgs*/nullptr,
11620 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011621
Douglas Gregor084d8552009-03-13 23:49:33 +000011622 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011623 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000011624
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011625 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11626
Douglas Gregor084d8552009-03-13 23:49:33 +000011627 // Perform overload resolution.
11628 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011629 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011630 case OR_Success: {
11631 // We found a built-in operator or an overloaded operator.
11632 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000011633
Douglas Gregor084d8552009-03-13 23:49:33 +000011634 if (FnDecl) {
11635 // We matched an overloaded operator. Build a call to that
11636 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000011637
Douglas Gregor084d8552009-03-13 23:49:33 +000011638 // Convert the arguments.
11639 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011640 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011641
John Wiegley01296292011-04-08 18:41:53 +000011642 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011643 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011644 Best->FoundDecl, Method);
11645 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011646 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011647 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011648 } else {
11649 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011650 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011651 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011652 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011653 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011654 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011655 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011656 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011657 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011658 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011659 }
11660
Douglas Gregor084d8552009-03-13 23:49:33 +000011661 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011662 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011663 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011664 if (FnExpr.isInvalid())
11665 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011666
Richard Smithc1564702013-11-15 02:58:23 +000011667 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011668 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011669 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11670 ResultTy = ResultTy.getNonLValueExprType(Context);
11671
Eli Friedman030eee42009-11-18 03:58:17 +000011672 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011673 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011674 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011675 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011676
Alp Toker314cc812014-01-25 16:55:45 +000011677 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011678 return ExprError();
11679
John McCallb268a282010-08-23 23:25:46 +000011680 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011681 } else {
11682 // We matched a built-in operator. Convert the arguments, then
11683 // break out so that we will build the appropriate built-in
11684 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011685 ExprResult InputRes =
11686 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11687 Best->Conversions[0], AA_Passing);
11688 if (InputRes.isInvalid())
11689 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011690 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011691 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011692 }
John Wiegley01296292011-04-08 18:41:53 +000011693 }
11694
11695 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011696 // This is an erroneous use of an operator which can be overloaded by
11697 // a non-member function. Check for non-member operators which were
11698 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011699 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011700 // FIXME: Recover by calling the found function.
11701 return ExprError();
11702
John Wiegley01296292011-04-08 18:41:53 +000011703 // No viable function; fall through to handling this as a
11704 // built-in operator, which will produce an error message for us.
11705 break;
11706
11707 case OR_Ambiguous:
11708 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11709 << UnaryOperator::getOpcodeStr(Opc)
11710 << Input->getType()
11711 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011712 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011713 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11714 return ExprError();
11715
11716 case OR_Deleted:
11717 Diag(OpLoc, diag::err_ovl_deleted_oper)
11718 << Best->Function->isDeleted()
11719 << UnaryOperator::getOpcodeStr(Opc)
11720 << getDeletedOrUnavailableSuffix(Best->Function)
11721 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011722 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011723 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011724 return ExprError();
11725 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011726
11727 // Either we found no viable overloaded operator or we matched a
11728 // built-in operator. In either case, fall through to trying to
11729 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011730 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011731}
11732
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011733/// \brief Create a binary operation that may resolve to an overloaded
11734/// operator.
11735///
11736/// \param OpLoc The location of the operator itself (e.g., '+').
11737///
Craig Toppera92ffb02015-12-10 08:51:49 +000011738/// \param Opc The BinaryOperatorKind that describes this operator.
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011739///
James Dennett18348b62012-06-22 08:52:37 +000011740/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011741/// considered by overload resolution. The caller needs to build this
11742/// set based on the context using, e.g.,
11743/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11744/// set should not contain any member functions; those will be added
11745/// by CreateOverloadedBinOp().
11746///
11747/// \param LHS Left-hand argument.
11748/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011749ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011750Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Craig Toppera92ffb02015-12-10 08:51:49 +000011751 BinaryOperatorKind Opc,
John McCall4c4c1df2010-01-26 03:27:55 +000011752 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011753 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011754 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011755 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011756
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011757 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11758 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11759
11760 // If either side is type-dependent, create an appropriate dependent
11761 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011762 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011763 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011764 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011765 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011766 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011767 return new (Context) BinaryOperator(
11768 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11769 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011770
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011771 return new (Context) CompoundAssignOperator(
11772 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11773 Context.DependentTy, Context.DependentTy, OpLoc,
11774 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011775 }
John McCall4c4c1df2010-01-26 03:27:55 +000011776
11777 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011778 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011779 // TODO: provide better source location info in DNLoc component.
11780 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011781 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011782 = UnresolvedLookupExpr::Create(Context, NamingClass,
11783 NestedNameSpecifierLoc(), OpNameInfo,
11784 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011785 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011786 return new (Context)
11787 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11788 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011789 }
11790
John McCall4124c492011-10-17 18:40:02 +000011791 // Always do placeholder-like conversions on the RHS.
11792 if (checkPlaceholderForOverload(*this, Args[1]))
11793 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011794
John McCall526ab472011-10-25 17:37:35 +000011795 // Do placeholder-like conversion on the LHS; note that we should
11796 // not get here with a PseudoObject LHS.
11797 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011798 if (checkPlaceholderForOverload(*this, Args[0]))
11799 return ExprError();
11800
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011801 // If this is the assignment operator, we only perform overload resolution
11802 // if the left-hand side is a class or enumeration type. This is actually
11803 // a hack. The standard requires that we do overload resolution between the
11804 // various built-in candidates, but as DR507 points out, this can lead to
11805 // problems. So we do it this way, which pretty much follows what GCC does.
11806 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011807 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011808 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011809
John McCalle26a8722010-12-04 08:14:53 +000011810 // If this is the .* operator, which is not overloadable, just
11811 // create a built-in binary operator.
11812 if (Opc == BO_PtrMemD)
11813 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11814
Douglas Gregor084d8552009-03-13 23:49:33 +000011815 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011816 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011817
11818 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011819 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011820
11821 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011822 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011823
Richard Smith0daabd72014-09-23 20:31:39 +000011824 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11825 // performed for an assignment operator (nor for operator[] nor operator->,
11826 // which don't get here).
11827 if (Opc != BO_Assign)
11828 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11829 /*ExplicitTemplateArgs*/ nullptr,
11830 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011831
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011832 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011833 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011834
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011835 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11836
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011837 // Perform overload resolution.
11838 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011839 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011840 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011841 // We found a built-in operator or an overloaded operator.
11842 FunctionDecl *FnDecl = Best->Function;
11843
11844 if (FnDecl) {
11845 // We matched an overloaded operator. Build a call to that
11846 // operator.
11847
11848 // Convert the arguments.
11849 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011850 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011851 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011852
Chandler Carruth8e543b32010-12-12 08:17:55 +000011853 ExprResult Arg1 =
11854 PerformCopyInitialization(
11855 InitializedEntity::InitializeParameter(Context,
11856 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011857 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011858 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011859 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011860
John Wiegley01296292011-04-08 18:41:53 +000011861 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011862 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011863 Best->FoundDecl, Method);
11864 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011865 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011866 Args[0] = Arg0.getAs<Expr>();
11867 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011868 } else {
11869 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011870 ExprResult Arg0 = PerformCopyInitialization(
11871 InitializedEntity::InitializeParameter(Context,
11872 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011873 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011874 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011875 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011876
Chandler Carruth8e543b32010-12-12 08:17:55 +000011877 ExprResult Arg1 =
11878 PerformCopyInitialization(
11879 InitializedEntity::InitializeParameter(Context,
11880 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011881 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011882 if (Arg1.isInvalid())
11883 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011884 Args[0] = LHS = Arg0.getAs<Expr>();
11885 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011886 }
11887
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011888 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011889 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011890 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011891 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011892 if (FnExpr.isInvalid())
11893 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011894
Richard Smithc1564702013-11-15 02:58:23 +000011895 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011896 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011897 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11898 ResultTy = ResultTy.getNonLValueExprType(Context);
11899
John McCallb268a282010-08-23 23:25:46 +000011900 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011901 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011902 Args, ResultTy, VK, OpLoc,
11903 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011904
Alp Toker314cc812014-01-25 16:55:45 +000011905 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011906 FnDecl))
11907 return ExprError();
11908
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011909 ArrayRef<const Expr *> ArgsArray(Args, 2);
11910 // Cut off the implicit 'this'.
11911 if (isa<CXXMethodDecl>(FnDecl))
11912 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011913
11914 // Check for a self move.
11915 if (Op == OO_Equal)
11916 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11917
Douglas Gregorb4866e82015-06-19 18:13:19 +000011918 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011919 TheCall->getSourceRange(), VariadicDoesNotApply);
11920
John McCallb268a282010-08-23 23:25:46 +000011921 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011922 } else {
11923 // We matched a built-in operator. Convert the arguments, then
11924 // break out so that we will build the appropriate built-in
11925 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011926 ExprResult ArgsRes0 =
11927 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11928 Best->Conversions[0], AA_Passing);
11929 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011930 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011931 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011932
John Wiegley01296292011-04-08 18:41:53 +000011933 ExprResult ArgsRes1 =
11934 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11935 Best->Conversions[1], AA_Passing);
11936 if (ArgsRes1.isInvalid())
11937 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011938 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011939 break;
11940 }
11941 }
11942
Douglas Gregor66950a32009-09-30 21:46:01 +000011943 case OR_No_Viable_Function: {
11944 // C++ [over.match.oper]p9:
11945 // If the operator is the operator , [...] and there are no
11946 // viable functions, then the operator is assumed to be the
11947 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011948 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011949 break;
11950
Chandler Carruth8e543b32010-12-12 08:17:55 +000011951 // For class as left operand for assignment or compound assigment
11952 // operator do not fall through to handling in built-in, but report that
11953 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011954 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011955 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011956 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011957 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11958 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011959 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011960 if (Args[0]->getType()->isIncompleteType()) {
11961 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11962 << Args[0]->getType()
11963 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11964 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011965 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011966 // This is an erroneous use of an operator which can be overloaded by
11967 // a non-member function. Check for non-member operators which were
11968 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011969 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011970 // FIXME: Recover by calling the found function.
11971 return ExprError();
11972
Douglas Gregor66950a32009-09-30 21:46:01 +000011973 // No viable function; try to create a built-in operation, which will
11974 // produce an error. Then, show the non-viable candidates.
11975 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011976 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011977 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011978 "C++ binary operator overloading is missing candidates!");
11979 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011980 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011981 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011982 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011983 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011984
11985 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011986 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011987 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011988 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011989 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011990 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011991 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011992 return ExprError();
11993
11994 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011995 if (isImplicitlyDeleted(Best->Function)) {
11996 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11997 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011998 << Context.getRecordType(Method->getParent())
11999 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000012000
Richard Smithde1a4872012-12-28 12:23:24 +000012001 // The user probably meant to call this special member. Just
12002 // explain why it's deleted.
12003 NoteDeletedFunction(Method);
12004 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000012005 } else {
12006 Diag(OpLoc, diag::err_ovl_deleted_oper)
12007 << Best->Function->isDeleted()
12008 << BinaryOperator::getOpcodeStr(Opc)
12009 << getDeletedOrUnavailableSuffix(Best->Function)
12010 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12011 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012012 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000012013 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012014 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000012015 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012016
Douglas Gregor66950a32009-09-30 21:46:01 +000012017 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000012018 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000012019}
12020
John McCalldadc5752010-08-24 06:29:42 +000012021ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000012022Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12023 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000012024 Expr *Base, Expr *Idx) {
12025 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000012026 DeclarationName OpName =
12027 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12028
12029 // If either side is type-dependent, create an appropriate dependent
12030 // expression.
12031 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12032
Craig Topperc3ec1492014-05-26 06:22:03 +000012033 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012034 // CHECKME: no 'operator' keyword?
12035 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12036 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000012037 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000012038 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000012039 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000012040 /*ADL*/ true, /*Overloaded*/ false,
12041 UnresolvedSetIterator(),
12042 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000012043 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000012044
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012045 return new (Context)
12046 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12047 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012048 }
12049
John McCall4124c492011-10-17 18:40:02 +000012050 // Handle placeholders on both operands.
12051 if (checkPlaceholderForOverload(*this, Args[0]))
12052 return ExprError();
12053 if (checkPlaceholderForOverload(*this, Args[1]))
12054 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012055
Sebastian Redladba46e2009-10-29 20:17:01 +000012056 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000012057 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000012058
12059 // Subscript can only be overloaded as a member function.
12060
12061 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000012062 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012063
12064 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000012065 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000012066
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012067 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12068
Sebastian Redladba46e2009-10-29 20:17:01 +000012069 // Perform overload resolution.
12070 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012071 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000012072 case OR_Success: {
12073 // We found a built-in operator or an overloaded operator.
12074 FunctionDecl *FnDecl = Best->Function;
12075
12076 if (FnDecl) {
12077 // We matched an overloaded operator. Build a call to that
12078 // operator.
12079
John McCalla0296f72010-03-19 07:35:19 +000012080 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000012081
Sebastian Redladba46e2009-10-29 20:17:01 +000012082 // Convert the arguments.
12083 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000012084 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000012085 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012086 Best->FoundDecl, Method);
12087 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012088 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012089 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012090
Anders Carlssona68e51e2010-01-29 18:37:50 +000012091 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000012092 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000012093 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012094 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000012095 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012096 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012097 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000012098 if (InputInit.isInvalid())
12099 return ExprError();
12100
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012101 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000012102
Sebastian Redladba46e2009-10-29 20:17:01 +000012103 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012104 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12105 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012106 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000012107 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012108 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012109 OpLocInfo.getLoc(),
12110 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012111 if (FnExpr.isInvalid())
12112 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012113
Richard Smithc1564702013-11-15 02:58:23 +000012114 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000012115 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000012116 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12117 ResultTy = ResultTy.getNonLValueExprType(Context);
12118
John McCallb268a282010-08-23 23:25:46 +000012119 CXXOperatorCallExpr *TheCall =
12120 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012121 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000012122 ResultTy, VK, RLoc,
12123 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000012124
Alp Toker314cc812014-01-25 16:55:45 +000012125 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000012126 return ExprError();
12127
John McCallb268a282010-08-23 23:25:46 +000012128 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000012129 } else {
12130 // We matched a built-in operator. Convert the arguments, then
12131 // break out so that we will build the appropriate built-in
12132 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000012133 ExprResult ArgsRes0 =
12134 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12135 Best->Conversions[0], AA_Passing);
12136 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000012137 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012138 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000012139
12140 ExprResult ArgsRes1 =
12141 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12142 Best->Conversions[1], AA_Passing);
12143 if (ArgsRes1.isInvalid())
12144 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012145 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000012146
12147 break;
12148 }
12149 }
12150
12151 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000012152 if (CandidateSet.empty())
12153 Diag(LLoc, diag::err_ovl_no_oper)
12154 << Args[0]->getType() << /*subscript*/ 0
12155 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12156 else
12157 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12158 << Args[0]->getType()
12159 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012160 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012161 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000012162 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000012163 }
12164
12165 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012166 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012167 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000012168 << Args[0]->getType() << Args[1]->getType()
12169 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012170 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012171 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012172 return ExprError();
12173
12174 case OR_Deleted:
12175 Diag(LLoc, diag::err_ovl_deleted_oper)
12176 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012177 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000012178 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012179 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000012180 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012181 return ExprError();
12182 }
12183
12184 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000012185 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000012186}
12187
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012188/// BuildCallToMemberFunction - Build a call to a member
12189/// function. MemExpr is the expression that refers to the member
12190/// function (and includes the object parameter), Args/NumArgs are the
12191/// arguments to the function call (not including the object
12192/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000012193/// expression refers to a non-static member function or an overloaded
12194/// member function.
John McCalldadc5752010-08-24 06:29:42 +000012195ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000012196Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012197 SourceLocation LParenLoc,
12198 MultiExprArg Args,
12199 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000012200 assert(MemExprE->getType() == Context.BoundMemberTy ||
12201 MemExprE->getType() == Context.OverloadTy);
12202
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012203 // Dig out the member expression. This holds both the object
12204 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000012205 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012206
John McCall0009fcc2011-04-26 20:42:42 +000012207 // Determine whether this is a call to a pointer-to-member function.
12208 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12209 assert(op->getType() == Context.BoundMemberTy);
12210 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12211
12212 QualType fnType =
12213 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12214
12215 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12216 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000012217 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000012218
12219 // Check that the object type isn't more qualified than the
12220 // member function we're calling.
12221 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12222
12223 QualType objectType = op->getLHS()->getType();
12224 if (op->getOpcode() == BO_PtrMemI)
12225 objectType = objectType->castAs<PointerType>()->getPointeeType();
12226 Qualifiers objectQuals = objectType.getQualifiers();
12227
12228 Qualifiers difference = objectQuals - funcQuals;
12229 difference.removeObjCGCAttr();
12230 difference.removeAddressSpace();
12231 if (difference) {
12232 std::string qualsString = difference.getAsString();
12233 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12234 << fnType.getUnqualifiedType()
12235 << qualsString
12236 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12237 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012238
John McCall0009fcc2011-04-26 20:42:42 +000012239 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012240 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000012241 resultType, valueKind, RParenLoc);
12242
Alp Toker314cc812014-01-25 16:55:45 +000012243 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012244 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000012245 return ExprError();
12246
Craig Topperc3ec1492014-05-26 06:22:03 +000012247 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000012248 return ExprError();
12249
Richard Trieu9be9c682013-06-22 02:30:38 +000012250 if (CheckOtherCall(call, proto))
12251 return ExprError();
12252
John McCall0009fcc2011-04-26 20:42:42 +000012253 return MaybeBindToTemporary(call);
12254 }
12255
David Majnemerced8bdf2015-02-25 17:36:15 +000012256 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12257 return new (Context)
12258 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12259
John McCall4124c492011-10-17 18:40:02 +000012260 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012261 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012262 return ExprError();
12263
John McCall10eae182009-11-30 22:42:35 +000012264 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000012265 CXXMethodDecl *Method = nullptr;
12266 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12267 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000012268 if (isa<MemberExpr>(NakedMemExpr)) {
12269 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000012270 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000012271 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012272 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000012273 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000012274 } else {
12275 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000012276 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012277
John McCall6e9f8f62009-12-03 04:06:58 +000012278 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000012279 Expr::Classification ObjectClassification
12280 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12281 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000012282
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012283 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000012284 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12285 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000012286
John McCall2d74de92009-12-01 22:10:20 +000012287 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012288 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012289 if (UnresExpr->hasExplicitTemplateArgs()) {
12290 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12291 TemplateArgs = &TemplateArgsBuffer;
12292 }
12293
John McCall10eae182009-11-30 22:42:35 +000012294 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12295 E = UnresExpr->decls_end(); I != E; ++I) {
12296
John McCall6e9f8f62009-12-03 04:06:58 +000012297 NamedDecl *Func = *I;
12298 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12299 if (isa<UsingShadowDecl>(Func))
12300 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12301
Douglas Gregor02824322011-01-26 19:30:28 +000012302
Francois Pichet64225792011-01-18 05:04:39 +000012303 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012304 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012305 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012306 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000012307 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000012308 // If explicit template arguments were provided, we can't call a
12309 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000012310 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000012311 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012312
John McCalla0296f72010-03-19 07:35:19 +000012313 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012314 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000012315 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012316 } else {
John McCall10eae182009-11-30 22:42:35 +000012317 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000012318 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012319 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012320 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012321 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000012322 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000012323 }
Mike Stump11289f42009-09-09 15:08:12 +000012324
John McCall10eae182009-11-30 22:42:35 +000012325 DeclarationName DeclName = UnresExpr->getMemberName();
12326
John McCall4124c492011-10-17 18:40:02 +000012327 UnbridgedCasts.restore();
12328
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012329 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012330 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000012331 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012332 case OR_Success:
12333 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000012334 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000012335 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012336 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12337 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012338 // If FoundDecl is different from Method (such as if one is a template
12339 // and the other a specialization), make sure DiagnoseUseOfDecl is
12340 // called on both.
12341 // FIXME: This would be more comprehensively addressed by modifying
12342 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12343 // being used.
12344 if (Method != FoundDecl.getDecl() &&
12345 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12346 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012347 break;
12348
12349 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000012350 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012351 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012352 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012353 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012354 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012355 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012356
12357 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000012358 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000012359 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012360 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012361 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012362 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012363
12364 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000012365 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000012366 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012367 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012368 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012369 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012370 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012371 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000012372 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012373 }
12374
John McCall16df1e52010-03-30 21:47:33 +000012375 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000012376
John McCall2d74de92009-12-01 22:10:20 +000012377 // If overload resolution picked a static member, build a
12378 // non-member call based on that function.
12379 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012380 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12381 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000012382 }
12383
John McCall10eae182009-11-30 22:42:35 +000012384 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012385 }
12386
Alp Toker314cc812014-01-25 16:55:45 +000012387 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012388 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12389 ResultType = ResultType.getNonLValueExprType(Context);
12390
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012391 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012392 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012393 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000012394 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012395
Anders Carlssonc4859ba2009-10-10 00:06:20 +000012396 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000012397 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000012398 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000012399 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012400
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012401 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000012402 // We only need to do this if there was actually an overload; otherwise
12403 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000012404 if (!Method->isStatic()) {
12405 ExprResult ObjectArg =
12406 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12407 FoundDecl, Method);
12408 if (ObjectArg.isInvalid())
12409 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012410 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000012411 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012412
12413 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000012414 const FunctionProtoType *Proto =
12415 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012416 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012417 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000012418 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012419
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012420 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012421
Richard Smith55ce3522012-06-25 20:30:08 +000012422 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000012423 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000012424
George Burgess IVaea6ade2015-09-25 17:53:16 +000012425 // In the case the method to call was not selected by the overloading
12426 // resolution process, we still need to handle the enable_if attribute. Do
12427 // that here, so it will not hide previous -- and more relevant -- errors
12428 if (isa<MemberExpr>(NakedMemExpr)) {
12429 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12430 Diag(MemExprE->getLocStart(),
12431 diag::err_ovl_no_viable_member_function_in_call)
12432 << Method << Method->getSourceRange();
12433 Diag(Method->getLocation(),
12434 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12435 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12436 return ExprError();
12437 }
12438 }
12439
Anders Carlsson47061ee2011-05-06 14:25:31 +000012440 if ((isa<CXXConstructorDecl>(CurContext) ||
12441 isa<CXXDestructorDecl>(CurContext)) &&
12442 TheCall->getMethodDecl()->isPure()) {
12443 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12444
Davide Italianoccb37382015-07-14 23:36:10 +000012445 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12446 MemExpr->performsVirtualDispatch(getLangOpts())) {
12447 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000012448 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12449 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12450 << MD->getParent()->getDeclName();
12451
12452 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000012453 if (getLangOpts().AppleKext)
12454 Diag(MemExpr->getLocStart(),
12455 diag::note_pure_qualified_call_kext)
12456 << MD->getParent()->getDeclName()
12457 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000012458 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000012459 }
Nico Weber5a9259c2016-01-15 21:45:31 +000012460
12461 if (CXXDestructorDecl *DD =
12462 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12463 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
Justin Lebard35f7062016-07-12 23:23:01 +000012464 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
Nico Weber5a9259c2016-01-15 21:45:31 +000012465 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12466 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12467 MemExpr->getMemberLoc());
12468 }
12469
John McCallb268a282010-08-23 23:25:46 +000012470 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000012471}
12472
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012473/// BuildCallToObjectOfClassType - Build a call to an object of class
12474/// type (C++ [over.call.object]), which can end up invoking an
12475/// overloaded function call operator (@c operator()) or performing a
12476/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000012477ExprResult
John Wiegley01296292011-04-08 18:41:53 +000012478Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000012479 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012480 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012481 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000012482 if (checkPlaceholderForOverload(*this, Obj))
12483 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012484 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000012485
12486 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012487 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000012488 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012489
Nico Weberb58e51c2014-11-19 05:21:39 +000012490 assert(Object.get()->getType()->isRecordType() &&
12491 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000012492 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000012493
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012494 // C++ [over.call.object]p1:
12495 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000012496 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012497 // candidate functions includes at least the function call
12498 // operators of T. The function call operators of T are obtained by
12499 // ordinary lookup of the name operator() in the context of
12500 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000012501 OverloadCandidateSet CandidateSet(LParenLoc,
12502 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000012503 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012504
John Wiegley01296292011-04-08 18:41:53 +000012505 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012506 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012507 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012508
John McCall27b18f82009-11-17 02:14:36 +000012509 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12510 LookupQualifiedName(R, Record->getDecl());
12511 R.suppressDiagnostics();
12512
Douglas Gregorc473cbb2009-11-15 07:48:03 +000012513 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000012514 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000012515 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012516 Object.get()->Classify(Context),
12517 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000012518 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000012519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012520
Douglas Gregorab7897a2008-11-19 22:57:39 +000012521 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012522 // In addition, for each (non-explicit in C++0x) conversion function
12523 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000012524 //
12525 // operator conversion-type-id () cv-qualifier;
12526 //
12527 // where cv-qualifier is the same cv-qualification as, or a
12528 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000012529 // denotes the type "pointer to function of (P1,...,Pn) returning
12530 // R", or the type "reference to pointer to function of
12531 // (P1,...,Pn) returning R", or the type "reference to function
12532 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000012533 // is also considered as a candidate function. Similarly,
12534 // surrogate call functions are added to the set of candidate
12535 // functions for each conversion function declared in an
12536 // accessible base class provided the function is not hidden
12537 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000012538 const auto &Conversions =
12539 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12540 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000012541 NamedDecl *D = *I;
12542 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12543 if (isa<UsingShadowDecl>(D))
12544 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012545
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012546 // Skip over templated conversion functions; they aren't
12547 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000012548 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000012549 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000012550
John McCall6e9f8f62009-12-03 04:06:58 +000012551 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012552 if (!Conv->isExplicit()) {
12553 // Strip the reference type (if any) and then the pointer type (if
12554 // any) to get down to what might be a function type.
12555 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12556 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12557 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000012558
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012559 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12560 {
12561 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012562 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000012563 }
12564 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000012565 }
Mike Stump11289f42009-09-09 15:08:12 +000012566
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012567 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12568
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012569 // Perform overload resolution.
12570 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000012571 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000012572 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012573 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000012574 // Overload resolution succeeded; we'll build the appropriate call
12575 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012576 break;
12577
12578 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000012579 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012580 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000012581 << Object.get()->getType() << /*call*/ 1
12582 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000012583 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012584 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000012585 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012586 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012587 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012588 break;
12589
12590 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012591 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012592 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000012593 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012594 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012595 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000012596
12597 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012598 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000012599 diag::err_ovl_deleted_object_call)
12600 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000012601 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012602 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000012603 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012604 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000012605 break;
Mike Stump11289f42009-09-09 15:08:12 +000012606 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012607
Douglas Gregorb412e172010-07-25 18:17:45 +000012608 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012609 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012610
John McCall4124c492011-10-17 18:40:02 +000012611 UnbridgedCasts.restore();
12612
Craig Topperc3ec1492014-05-26 06:22:03 +000012613 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000012614 // Since there is no function declaration, this is one of the
12615 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000012616 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000012617 = cast<CXXConversionDecl>(
12618 Best->Conversions[0].UserDefined.ConversionFunction);
12619
Craig Topperc3ec1492014-05-26 06:22:03 +000012620 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12621 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000012622 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12623 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000012624 assert(Conv == Best->FoundDecl.getDecl() &&
12625 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000012626 // We selected one of the surrogate functions that converts the
12627 // object parameter to a function pointer. Perform the conversion
12628 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012629
Fariborz Jahanian774cf792009-09-28 18:35:46 +000012630 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000012631 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012632 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12633 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000012634 if (Call.isInvalid())
12635 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000012636 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012637 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12638 CK_UserDefinedConversion, Call.get(),
12639 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012640
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012641 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000012642 }
12643
Craig Topperc3ec1492014-05-26 06:22:03 +000012644 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000012645
Douglas Gregorab7897a2008-11-19 22:57:39 +000012646 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12647 // that calls this method, using Object for the implicit object
12648 // parameter and passing along the remaining arguments.
12649 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012650
12651 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012652 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012653 return ExprError();
12654
Chandler Carruth8e543b32010-12-12 08:17:55 +000012655 const FunctionProtoType *Proto =
12656 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012657
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012658 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012659
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012660 DeclarationNameInfo OpLocInfo(
12661 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12662 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012663 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012664 HadMultipleCandidates,
12665 OpLocInfo.getLoc(),
12666 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012667 if (NewFn.isInvalid())
12668 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012669
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012670 // Build the full argument list for the method call (the implicit object
12671 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012672 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012673 MethodArgs[0] = Object.get();
12674 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12675
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012676 // Once we've built TheCall, all of the expressions are properly
12677 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012678 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012679 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12680 ResultTy = ResultTy.getNonLValueExprType(Context);
12681
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012682 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012683 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012684 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12685 ResultTy, VK, RParenLoc, false);
12686 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012687
Alp Toker314cc812014-01-25 16:55:45 +000012688 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012689 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012690
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012691 // We may have default arguments. If so, we need to allocate more
12692 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012693 if (Args.size() < NumParams)
12694 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012695
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012696 bool IsError = false;
12697
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012698 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012699 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012700 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012701 Best->FoundDecl, Method);
12702 if (ObjRes.isInvalid())
12703 IsError = true;
12704 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012705 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012706 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012707
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012708 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012709 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012710 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012711 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012712 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012713
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012714 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012715
John McCalldadc5752010-08-24 06:29:42 +000012716 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012717 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012718 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012719 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012720 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012721
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012722 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012723 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012724 } else {
John McCalldadc5752010-08-24 06:29:42 +000012725 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012726 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12727 if (DefArg.isInvalid()) {
12728 IsError = true;
12729 break;
12730 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012731
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012732 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012733 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012734
12735 TheCall->setArg(i + 1, Arg);
12736 }
12737
12738 // If this is a variadic call, handle args passed through "...".
12739 if (Proto->isVariadic()) {
12740 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012741 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012742 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12743 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012744 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012745 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012746 }
12747 }
12748
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012749 if (IsError) return true;
12750
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012751 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012752
Richard Smith55ce3522012-06-25 20:30:08 +000012753 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012754 return true;
12755
John McCalle172be52010-08-24 06:09:16 +000012756 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012757}
12758
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012759/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012760/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012761/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012762ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012763Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12764 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012765 assert(Base->getType()->isRecordType() &&
12766 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012767
John McCall4124c492011-10-17 18:40:02 +000012768 if (checkPlaceholderForOverload(*this, Base))
12769 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012770
John McCallbc077cf2010-02-08 23:07:23 +000012771 SourceLocation Loc = Base->getExprLoc();
12772
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012773 // C++ [over.ref]p1:
12774 //
12775 // [...] An expression x->m is interpreted as (x.operator->())->m
12776 // for a class object x of type T if T::operator->() exists and if
12777 // the operator is selected as the best match function by the
12778 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012779 DeclarationName OpName =
12780 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012781 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012782 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012783
John McCallbc077cf2010-02-08 23:07:23 +000012784 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012785 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012786 return ExprError();
12787
John McCall27b18f82009-11-17 02:14:36 +000012788 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12789 LookupQualifiedName(R, BaseRecord->getDecl());
12790 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012791
12792 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012793 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012794 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012795 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012796 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012797
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012798 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12799
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012800 // Perform overload resolution.
12801 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012802 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012803 case OR_Success:
12804 // Overload resolution succeeded; we'll build the call below.
12805 break;
12806
12807 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012808 if (CandidateSet.empty()) {
12809 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012810 if (NoArrowOperatorFound) {
12811 // Report this specific error to the caller instead of emitting a
12812 // diagnostic, as requested.
12813 *NoArrowOperatorFound = true;
12814 return ExprError();
12815 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012816 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12817 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012818 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012819 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012820 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012821 }
12822 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012823 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012824 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012825 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012826 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012827
12828 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012829 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12830 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012831 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012832 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012833
12834 case OR_Deleted:
12835 Diag(OpLoc, diag::err_ovl_deleted_oper)
12836 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012837 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012838 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012839 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012840 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012841 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012842 }
12843
Craig Topperc3ec1492014-05-26 06:22:03 +000012844 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012845
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012846 // Convert the object parameter.
12847 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012848 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012849 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012850 Best->FoundDecl, Method);
12851 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012852 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012853 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012854
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012855 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012856 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012857 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012858 if (FnExpr.isInvalid())
12859 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012860
Alp Toker314cc812014-01-25 16:55:45 +000012861 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012862 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12863 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012864 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012865 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012866 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012867
Alp Toker314cc812014-01-25 16:55:45 +000012868 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012869 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012870
12871 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012872}
12873
Richard Smithbcc22fc2012-03-09 08:00:36 +000012874/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12875/// a literal operator described by the provided lookup results.
12876ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12877 DeclarationNameInfo &SuffixInfo,
12878 ArrayRef<Expr*> Args,
12879 SourceLocation LitEndLoc,
12880 TemplateArgumentListInfo *TemplateArgs) {
12881 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012882
Richard Smith100b24a2014-04-17 01:52:14 +000012883 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12884 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012885 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12886 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012887
Richard Smithbcc22fc2012-03-09 08:00:36 +000012888 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12889
Richard Smithbcc22fc2012-03-09 08:00:36 +000012890 // Perform overload resolution. This will usually be trivial, but might need
12891 // to perform substitutions for a literal operator template.
12892 OverloadCandidateSet::iterator Best;
12893 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12894 case OR_Success:
12895 case OR_Deleted:
12896 break;
12897
12898 case OR_No_Viable_Function:
12899 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12900 << R.getLookupName();
12901 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12902 return ExprError();
12903
12904 case OR_Ambiguous:
12905 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12906 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12907 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012908 }
12909
Richard Smithbcc22fc2012-03-09 08:00:36 +000012910 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012911 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12912 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012913 SuffixInfo.getLoc(),
12914 SuffixInfo.getInfo());
12915 if (Fn.isInvalid())
12916 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012917
12918 // Check the argument types. This should almost always be a no-op, except
12919 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012920 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012921 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012922 ExprResult InputInit = PerformCopyInitialization(
12923 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12924 SourceLocation(), Args[ArgIdx]);
12925 if (InputInit.isInvalid())
12926 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012927 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012928 }
12929
Alp Toker314cc812014-01-25 16:55:45 +000012930 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012931 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12932 ResultTy = ResultTy.getNonLValueExprType(Context);
12933
Richard Smithc67fdd42012-03-07 08:35:16 +000012934 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012935 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012936 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012937 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12938
Alp Toker314cc812014-01-25 16:55:45 +000012939 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012940 return ExprError();
12941
Craig Topperc3ec1492014-05-26 06:22:03 +000012942 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012943 return ExprError();
12944
12945 return MaybeBindToTemporary(UDL);
12946}
12947
Sam Panzer0f384432012-08-21 00:52:01 +000012948/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12949/// given LookupResult is non-empty, it is assumed to describe a member which
12950/// will be invoked. Otherwise, the function will be found via argument
12951/// dependent lookup.
12952/// CallExpr is set to a valid expression and FRS_Success returned on success,
12953/// otherwise CallExpr is set to ExprError() and some non-success value
12954/// is returned.
12955Sema::ForRangeStatus
Richard Smith9f690bd2015-10-27 06:02:45 +000012956Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12957 SourceLocation RangeLoc,
Sam Panzer0f384432012-08-21 00:52:01 +000012958 const DeclarationNameInfo &NameInfo,
12959 LookupResult &MemberLookup,
12960 OverloadCandidateSet *CandidateSet,
12961 Expr *Range, ExprResult *CallExpr) {
Richard Smith9f690bd2015-10-27 06:02:45 +000012962 Scope *S = nullptr;
12963
Sam Panzer0f384432012-08-21 00:52:01 +000012964 CandidateSet->clear();
12965 if (!MemberLookup.empty()) {
12966 ExprResult MemberRef =
12967 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12968 /*IsPtr=*/false, CXXScopeSpec(),
12969 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012970 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012971 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012972 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012973 if (MemberRef.isInvalid()) {
12974 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012975 return FRS_DiagnosticIssued;
12976 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012977 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012978 if (CallExpr->isInvalid()) {
12979 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000012980 return FRS_DiagnosticIssued;
12981 }
12982 } else {
12983 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012984 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012985 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012986 NestedNameSpecifierLoc(), NameInfo,
12987 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012988 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012989
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012990 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012991 CandidateSet, CallExpr);
12992 if (CandidateSet->empty() || CandidateSetError) {
12993 *CallExpr = ExprError();
12994 return FRS_NoViableFunction;
12995 }
12996 OverloadCandidateSet::iterator Best;
12997 OverloadingResult OverloadResult =
12998 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12999
13000 if (OverloadResult == OR_No_Viable_Function) {
13001 *CallExpr = ExprError();
13002 return FRS_NoViableFunction;
13003 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000013004 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000013005 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000013006 OverloadResult,
13007 /*AllowTypoCorrection=*/false);
13008 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13009 *CallExpr = ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000013010 return FRS_DiagnosticIssued;
13011 }
13012 }
13013 return FRS_Success;
13014}
13015
13016
Douglas Gregorcd695e52008-11-10 20:40:00 +000013017/// FixOverloadedFunctionReference - E is an expression that refers to
13018/// a C++ overloaded function (possibly with some parentheses and
13019/// perhaps a '&' around it). We have resolved the overloaded function
13020/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000013021/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000013022Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000013023 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000013024 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013025 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13026 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013027 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013028 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013029
Douglas Gregor51c538b2009-11-20 19:42:02 +000013030 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013031 }
13032
Douglas Gregor51c538b2009-11-20 19:42:02 +000013033 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000013034 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13035 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013036 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000013037 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000013038 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000013039 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000013040 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013041 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013042
13043 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000013044 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013045 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013046 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013047 }
13048
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013049 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13050 if (!GSE->isResultDependent()) {
13051 Expr *SubExpr =
13052 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13053 if (SubExpr == GSE->getResultExpr())
13054 return GSE;
13055
13056 // Replace the resulting type information before rebuilding the generic
13057 // selection expression.
Aaron Ballman8b871d92016-09-02 18:31:31 +000013058 ArrayRef<Expr *> A = GSE->getAssocExprs();
13059 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
Aaron Ballmanff7bd8b2016-09-02 13:45:40 +000013060 unsigned ResultIdx = GSE->getResultIndex();
13061 AssocExprs[ResultIdx] = SubExpr;
13062
13063 return new (Context) GenericSelectionExpr(
13064 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13065 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13066 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13067 ResultIdx);
13068 }
13069 // Rather than fall through to the unreachable, return the original generic
13070 // selection expression.
13071 return GSE;
13072 }
13073
Douglas Gregor51c538b2009-11-20 19:42:02 +000013074 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000013075 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000013076 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013077 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13078 if (Method->isStatic()) {
13079 // Do nothing: static member functions aren't any different
13080 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000013081 } else {
Alp Toker028ed912013-12-06 17:56:43 +000013082 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000013083 // UnresolvedLookupExpr holding an overloaded member function
13084 // or template.
John McCall16df1e52010-03-30 21:47:33 +000013085 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13086 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000013087 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013088 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013089
John McCalld14a8642009-11-21 08:51:07 +000013090 assert(isa<DeclRefExpr>(SubExpr)
13091 && "fixed to something other than a decl ref");
13092 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13093 && "fixed to a member ref with no nested name qualifier");
13094
13095 // We have taken the address of a pointer to member
13096 // function. Perform the computation here so that we get the
13097 // appropriate pointer to member type.
13098 QualType ClassType
13099 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13100 QualType MemPtrType
13101 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
David Majnemer02d57cc2016-06-30 03:02:03 +000013102 // Under the MS ABI, lock down the inheritance model now.
13103 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13104 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
John McCalld14a8642009-11-21 08:51:07 +000013105
John McCall7decc9e2010-11-18 06:31:45 +000013106 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13107 VK_RValue, OK_Ordinary,
13108 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000013109 }
13110 }
John McCall16df1e52010-03-30 21:47:33 +000013111 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13112 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000013113 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000013114 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013115
John McCalle3027922010-08-25 11:45:40 +000013116 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013117 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000013118 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000013119 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013120 }
John McCalld14a8642009-11-21 08:51:07 +000013121
13122 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000013123 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013124 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000013125 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000013126 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13127 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000013128 }
13129
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013130 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13131 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013132 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013133 Fn,
John McCall113bee02012-03-10 09:33:50 +000013134 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013135 ULE->getNameLoc(),
13136 Fn->getType(),
13137 VK_LValue,
13138 Found.getDecl(),
13139 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013140 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013141 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13142 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000013143 }
13144
John McCall10eae182009-11-30 22:42:35 +000013145 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000013146 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000013147 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000013148 if (MemExpr->hasExplicitTemplateArgs()) {
13149 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13150 TemplateArgs = &TemplateArgsBuffer;
13151 }
John McCall6b51f282009-11-23 01:53:49 +000013152
John McCall2d74de92009-12-01 22:10:20 +000013153 Expr *Base;
13154
John McCall7decc9e2010-11-18 06:31:45 +000013155 // If we're filling in a static method where we used to have an
13156 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000013157 if (MemExpr->isImplicitAccess()) {
13158 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013159 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13160 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000013161 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013162 Fn,
John McCall113bee02012-03-10 09:33:50 +000013163 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013164 MemExpr->getMemberLoc(),
13165 Fn->getType(),
13166 VK_LValue,
13167 Found.getDecl(),
13168 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000013169 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000013170 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13171 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000013172 } else {
13173 SourceLocation Loc = MemExpr->getMemberLoc();
13174 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000013175 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000013176 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000013177 Base = new (Context) CXXThisExpr(Loc,
13178 MemExpr->getBaseType(),
13179 /*isImplicit=*/true);
13180 }
John McCall2d74de92009-12-01 22:10:20 +000013181 } else
John McCallc3007a22010-10-26 07:05:15 +000013182 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000013183
John McCall4adb38c2011-04-27 00:36:17 +000013184 ExprValueKind valueKind;
13185 QualType type;
13186 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13187 valueKind = VK_LValue;
13188 type = Fn->getType();
13189 } else {
13190 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000013191 type = Context.BoundMemberTy;
13192 }
13193
13194 MemberExpr *ME = MemberExpr::Create(
13195 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13196 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13197 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13198 OK_Ordinary);
13199 ME->setHadMultipleCandidates(true);
13200 MarkMemberReferenced(ME);
13201 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000013202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013203
John McCallc3007a22010-10-26 07:05:15 +000013204 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000013205}
13206
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000013207ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000013208 DeclAccessPair Found,
13209 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013210 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000013211}