blob: 96107db520ffbc2dea758c93c99c8b8c74d3504b [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
Nick Lewycky134af912013-02-07 05:08:22 +000041/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000042static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000043CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000045 SourceLocation Loc = SourceLocation(),
46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000047 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000048 return ExprError();
49 // If FoundDecl is different from Fn (such as if one is a template
50 // and the other a specialization), make sure DiagnoseUseOfDecl is
51 // called on both.
52 // FIXME: This would be more comprehensively addressed by modifying
53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
54 // being used.
55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000056 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000057 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000058 VK_LValue, Loc, LocInfo);
59 if (HadMultipleCandidates)
60 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000061
62 S.MarkDeclRefReferenced(DRE);
Nick Lewycky134af912013-02-07 05:08:22 +000063
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000064 ExprResult E = DRE;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000065 E = S.DefaultFunctionArrayConversion(E.get());
John Wiegley01296292011-04-08 18:41:53 +000066 if (E.isInvalid())
67 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000068 return E;
John McCall7decc9e2010-11-18 06:31:45 +000069}
70
John McCall5c32be02010-08-24 20:38:10 +000071static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000073 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000074 bool CStyle,
75 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000076
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000077static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
78 QualType &ToType,
79 bool InOverloadResolution,
80 StandardConversionSequence &SCS,
81 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000082static OverloadingResult
83IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84 UserDefinedConversionSequence& User,
85 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000086 bool AllowExplicit,
87 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000088
89
90static ImplicitConversionSequence::CompareKind
91CompareStandardConversionSequences(Sema &S,
92 const StandardConversionSequence& SCS1,
93 const StandardConversionSequence& SCS2);
94
95static ImplicitConversionSequence::CompareKind
96CompareQualificationConversions(Sema &S,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareDerivedToBaseConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105/// GetConversionRank - Retrieve the implicit conversion rank
106/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000107ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 static const ImplicitConversionRank
109 Rank[(int)ICK_Num_Conversion_Kinds] = {
110 ICR_Exact_Match,
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000115 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICR_Promotion,
117 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000118 ICR_Promotion,
119 ICR_Conversion,
120 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000126 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000127 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000128 ICR_Conversion,
129 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000130 ICR_Complex_Real_Conversion,
131 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000132 ICR_Conversion,
133 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134 };
135 return Rank[(int)Kind];
136}
137
138/// GetImplicitConversionName - Return the name of this kind of
139/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000140static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000141 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000142 "No conversion",
143 "Lvalue-to-rvalue",
144 "Array-to-pointer",
145 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000146 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 "Qualification",
148 "Integral promotion",
149 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000150 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 "Integral conversion",
152 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000153 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000154 "Floating-integral conversion",
155 "Pointer conversion",
156 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000157 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000158 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000159 "Derived-to-base conversion",
160 "Vector conversion",
161 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000162 "Complex-real conversion",
163 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000164 "Transparent Union Conversion",
John McCall31168b02011-06-15 23:02:42 +0000165 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000166 };
167 return Name[Kind];
168}
169
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000170/// StandardConversionSequence - Set the standard conversion
171/// sequence to the identity conversion.
172void StandardConversionSequence::setAsIdentityConversion() {
173 First = ICK_Identity;
174 Second = ICK_Identity;
175 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000176 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000177 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000178 ReferenceBinding = false;
179 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000180 IsLvalueReference = true;
181 BindsToFunctionLvalue = false;
182 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000183 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000184 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000186}
187
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000188/// getRank - Retrieve the rank of this standard conversion sequence
189/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
190/// implicit conversions.
191ImplicitConversionRank StandardConversionSequence::getRank() const {
192 ImplicitConversionRank Rank = ICR_Exact_Match;
193 if (GetConversionRank(First) > Rank)
194 Rank = GetConversionRank(First);
195 if (GetConversionRank(Second) > Rank)
196 Rank = GetConversionRank(Second);
197 if (GetConversionRank(Third) > Rank)
198 Rank = GetConversionRank(Third);
199 return Rank;
200}
201
202/// isPointerConversionToBool - Determines whether this conversion is
203/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000204/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000206bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000207 // Note that FromType has not necessarily been transformed by the
208 // array-to-pointer or function-to-pointer implicit conversions, so
209 // check for their presence as well as checking whether FromType is
210 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000211 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000212 (getFromType()->isPointerType() ||
213 getFromType()->isObjCObjectPointerType() ||
214 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000215 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000216 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
217 return true;
218
219 return false;
220}
221
Douglas Gregor5c407d92008-10-23 00:40:37 +0000222/// isPointerConversionToVoidPointer - Determines whether this
223/// conversion is a conversion of a pointer to a void pointer. This is
224/// used as part of the ranking of standard conversion sequences (C++
225/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000226bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000227StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000228isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000229 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000230 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000231
232 // Note that FromType has not necessarily been transformed by the
233 // array-to-pointer implicit conversion, so check for its presence
234 // and redo the conversion to get a pointer.
235 if (First == ICK_Array_To_Pointer)
236 FromType = Context.getArrayDecayedType(FromType);
237
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000238 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000239 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240 return ToPtrType->getPointeeType()->isVoidType();
241
242 return false;
243}
244
Richard Smith66e05fe2012-01-18 05:21:49 +0000245/// Skip any implicit casts which could be either part of a narrowing conversion
246/// or after one in an implicit conversion.
247static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
248 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
249 switch (ICE->getCastKind()) {
250 case CK_NoOp:
251 case CK_IntegralCast:
252 case CK_IntegralToBoolean:
253 case CK_IntegralToFloating:
254 case CK_FloatingToIntegral:
255 case CK_FloatingToBoolean:
256 case CK_FloatingCast:
257 Converted = ICE->getSubExpr();
258 continue;
259
260 default:
261 return Converted;
262 }
263 }
264
265 return Converted;
266}
267
268/// Check if this standard conversion sequence represents a narrowing
269/// conversion, according to C++11 [dcl.init.list]p7.
270///
271/// \param Ctx The AST context.
272/// \param Converted The result of applying this standard conversion sequence.
273/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
274/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000275/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
276/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000277NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000278StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
279 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000280 APValue &ConstantValue,
281 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000282 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000283
284 // C++11 [dcl.init.list]p7:
285 // A narrowing conversion is an implicit conversion ...
286 QualType FromType = getToType(0);
287 QualType ToType = getToType(1);
288 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000289 // 'bool' is an integral type; dispatch to the right place to handle it.
290 case ICK_Boolean_Conversion:
291 if (FromType->isRealFloatingType())
292 goto FloatingIntegralConversion;
293 if (FromType->isIntegralOrUnscopedEnumerationType())
294 goto IntegralConversion;
295 // Boolean conversions can be from pointers and pointers to members
296 // [conv.bool], and those aren't considered narrowing conversions.
297 return NK_Not_Narrowing;
298
Richard Smith66e05fe2012-01-18 05:21:49 +0000299 // -- from a floating-point type to an integer type, or
300 //
301 // -- from an integer type or unscoped enumeration type to a floating-point
302 // type, except where the source is a constant expression and the actual
303 // value after conversion will fit into the target type and will produce
304 // the original value when converted back to the original type, or
305 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000306 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000307 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
308 return NK_Type_Narrowing;
309 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
310 llvm::APSInt IntConstantValue;
311 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
312 if (Initializer &&
313 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
314 // Convert the integer to the floating type.
315 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
316 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
317 llvm::APFloat::rmNearestTiesToEven);
318 // And back.
319 llvm::APSInt ConvertedValue = IntConstantValue;
320 bool ignored;
321 Result.convertToInteger(ConvertedValue,
322 llvm::APFloat::rmTowardZero, &ignored);
323 // If the resulting value is different, this was a narrowing conversion.
324 if (IntConstantValue != ConvertedValue) {
325 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000326 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000327 return NK_Constant_Narrowing;
328 }
329 } else {
330 // Variables are always narrowings.
331 return NK_Variable_Narrowing;
332 }
333 }
334 return NK_Not_Narrowing;
335
336 // -- from long double to double or float, or from double to float, except
337 // where the source is a constant expression and the actual value after
338 // conversion is within the range of values that can be represented (even
339 // if it cannot be represented exactly), or
340 case ICK_Floating_Conversion:
341 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
342 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
343 // FromType is larger than ToType.
344 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
345 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
346 // Constant!
347 assert(ConstantValue.isFloat());
348 llvm::APFloat FloatVal = ConstantValue.getFloat();
349 // Convert the source value into the target type.
350 bool ignored;
351 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
352 Ctx.getFloatTypeSemantics(ToType),
353 llvm::APFloat::rmNearestTiesToEven, &ignored);
354 // If there was no overflow, the source value is within the range of
355 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000356 if (ConvertStatus & llvm::APFloat::opOverflow) {
357 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000358 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000359 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000360 } else {
361 return NK_Variable_Narrowing;
362 }
363 }
364 return NK_Not_Narrowing;
365
366 // -- from an integer type or unscoped enumeration type to an integer type
367 // that cannot represent all the values of the original type, except where
368 // the source is a constant expression and the actual value after
369 // conversion will fit into the target type and will produce the original
370 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000371 case ICK_Integral_Conversion:
372 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000373 assert(FromType->isIntegralOrUnscopedEnumerationType());
374 assert(ToType->isIntegralOrUnscopedEnumerationType());
375 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
376 const unsigned FromWidth = Ctx.getIntWidth(FromType);
377 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
378 const unsigned ToWidth = Ctx.getIntWidth(ToType);
379
380 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000381 (FromWidth == ToWidth && FromSigned != ToSigned) ||
382 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000383 // Not all values of FromType can be represented in ToType.
384 llvm::APSInt InitializerValue;
385 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000386 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
387 // Such conversions on variables are always narrowing.
388 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000389 }
390 bool Narrowing = false;
391 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000392 // Negative -> unsigned is narrowing. Otherwise, more bits is never
393 // narrowing.
394 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000395 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000396 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000397 // Add a bit to the InitializerValue so we don't have to worry about
398 // signed vs. unsigned comparisons.
399 InitializerValue = InitializerValue.extend(
400 InitializerValue.getBitWidth() + 1);
401 // Convert the initializer to and from the target width and signed-ness.
402 llvm::APSInt ConvertedValue = InitializerValue;
403 ConvertedValue = ConvertedValue.trunc(ToWidth);
404 ConvertedValue.setIsSigned(ToSigned);
405 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
406 ConvertedValue.setIsSigned(InitializerValue.isSigned());
407 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000408 if (ConvertedValue != InitializerValue)
409 Narrowing = true;
410 }
411 if (Narrowing) {
412 ConstantType = Initializer->getType();
413 ConstantValue = APValue(InitializerValue);
414 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000415 }
416 }
417 return NK_Not_Narrowing;
418 }
419
420 default:
421 // Other kinds of conversions are not narrowings.
422 return NK_Not_Narrowing;
423 }
424}
425
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000426/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000427/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000428void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000429 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000430 bool PrintedSomething = false;
431 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000432 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000433 PrintedSomething = true;
434 }
435
436 if (Second != ICK_Identity) {
437 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000438 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000439 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000440 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000441
442 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000443 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000444 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000445 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000446 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000447 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000448 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000449 PrintedSomething = true;
450 }
451
452 if (Third != ICK_Identity) {
453 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000454 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000455 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000456 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 PrintedSomething = true;
458 }
459
460 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000461 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000462 }
463}
464
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000465/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000467void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000468 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000470 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000471 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000472 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000473 if (ConversionFunction)
474 OS << '\'' << *ConversionFunction << '\'';
475 else
476 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000478 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000479 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 }
481}
482
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000483/// dump - Print this implicit 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 ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000486 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000487 if (isStdInitializerListElement())
488 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 switch (ConversionKind) {
490 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000491 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000492 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493 break;
494 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000495 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000496 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 break;
498 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 break;
John McCall0d1da222010-01-12 00:44:57 +0000501 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000502 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000503 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 break;
507 }
508
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000509 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510}
511
John McCall0d1da222010-01-12 00:44:57 +0000512void AmbiguousConversionSequence::construct() {
513 new (&conversions()) ConversionSet();
514}
515
516void AmbiguousConversionSequence::destruct() {
517 conversions().~ConversionSet();
518}
519
520void
521AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
522 FromTypePtr = O.FromTypePtr;
523 ToTypePtr = O.ToTypePtr;
524 new (&conversions()) ConversionSet(O.conversions());
525}
526
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000527namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000528 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000529 // template argument information.
530 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000531 TemplateArgument FirstArg;
532 TemplateArgument SecondArg;
533 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000534 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000535 // template parameter and template argument information.
536 struct DFIParamWithArguments : DFIArguments {
537 TemplateParameter Param;
538 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000539}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000540
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000541/// \brief Convert from Sema's representation of template deduction information
542/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000543DeductionFailureInfo
544clang::MakeDeductionFailureInfo(ASTContext &Context,
545 Sema::TemplateDeductionResult TDK,
546 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000547 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000548 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000549 Result.HasDiagnostic = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000550 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000551 switch (TDK) {
552 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000553 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000554 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000555 case Sema::TDK_TooManyArguments:
556 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000557 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000559 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000560 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000561 Result.Data = Info.Param.getOpaqueValue();
562 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
Richard Smith44ecdbd2013-01-31 05:19:49 +0000564 case Sema::TDK_NonDeducedMismatch: {
565 // FIXME: Should allocate from normal heap so that we can free this later.
566 DFIArguments *Saved = new (Context) DFIArguments;
567 Saved->FirstArg = Info.FirstArg;
568 Saved->SecondArg = Info.SecondArg;
569 Result.Data = Saved;
570 break;
571 }
572
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000573 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000574 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000575 // FIXME: Should allocate from normal heap so that we can free this later.
576 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000577 Saved->Param = Info.Param;
578 Saved->FirstArg = Info.FirstArg;
579 Saved->SecondArg = Info.SecondArg;
580 Result.Data = Saved;
581 break;
582 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000584 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000585 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000586 if (Info.hasSFINAEDiagnostic()) {
587 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
588 SourceLocation(), PartialDiagnostic::NullDiagnostic());
589 Info.takeSFINAEDiagnostic(*Diag);
590 Result.HasDiagnostic = true;
591 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000592 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000595 Result.Data = Info.Expression;
596 break;
597
Richard Smith44ecdbd2013-01-31 05:19:49 +0000598 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 return Result;
603}
John McCall0d1da222010-01-12 00:44:57 +0000604
Larisse Voufo98b20f12013-07-19 23:00:19 +0000605void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000606 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
607 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000608 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 case Sema::TDK_InstantiationDepth:
610 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000611 case Sema::TDK_TooManyArguments:
612 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000613 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000614 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000617 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000618 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000619 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000620 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000621 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000622 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000623
624 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000625 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000626 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000627 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
628 Diag->~PartialDiagnosticAt();
629 HasDiagnostic = false;
630 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000631 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632
Douglas Gregor461761d2010-05-08 18:20:53 +0000633 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000634 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000635 break;
636 }
637}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Larisse Voufo98b20f12013-07-19 23:00:19 +0000639PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000640 if (HasDiagnostic)
641 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000642 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000643}
644
Larisse Voufo98b20f12013-07-19 23:00:19 +0000645TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000646 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
647 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000648 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000649 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000650 case Sema::TDK_TooManyArguments:
651 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000652 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000653 case Sema::TDK_NonDeducedMismatch:
654 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000655 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000657 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000658 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660
661 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000662 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000663 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000665 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000666 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000667 break;
668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000670 return TemplateParameter();
671}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672
Larisse Voufo98b20f12013-07-19 23:00:19 +0000673TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000674 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000675 case Sema::TDK_Success:
676 case Sema::TDK_Invalid:
677 case Sema::TDK_InstantiationDepth:
678 case Sema::TDK_TooManyArguments:
679 case Sema::TDK_TooFewArguments:
680 case Sema::TDK_Incomplete:
681 case Sema::TDK_InvalidExplicitArguments:
682 case Sema::TDK_Inconsistent:
683 case Sema::TDK_Underqualified:
684 case Sema::TDK_NonDeducedMismatch:
685 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000686 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000687
Richard Smith44ecdbd2013-01-31 05:19:49 +0000688 case Sema::TDK_SubstitutionFailure:
689 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000690
Richard Smith44ecdbd2013-01-31 05:19:49 +0000691 // Unhandled
692 case Sema::TDK_MiscellaneousDeductionFailure:
693 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000694 }
695
Craig Topperc3ec1492014-05-26 06:22:03 +0000696 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000697}
698
Larisse Voufo98b20f12013-07-19 23:00:19 +0000699const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
701 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000702 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000707 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000708 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000709 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000710 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000711
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000712 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000713 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000714 case Sema::TDK_NonDeducedMismatch:
715 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000716
Douglas Gregor461761d2010-05-08 18:20:53 +0000717 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000718 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000719 break;
720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721
Craig Topperc3ec1492014-05-26 06:22:03 +0000722 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000724
Larisse Voufo98b20f12013-07-19 23:00:19 +0000725const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000728 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000733 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000734 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000735 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000736 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000737
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000739 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000742
Douglas Gregor461761d2010-05-08 18:20:53 +0000743 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000744 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000745 break;
746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000747
Craig Topperc3ec1492014-05-26 06:22:03 +0000748 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000749}
750
Larisse Voufo98b20f12013-07-19 23:00:19 +0000751Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000752 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
753 Sema::TDK_FailedOverloadResolution)
754 return static_cast<Expr*>(Data);
755
Craig Topperc3ec1492014-05-26 06:22:03 +0000756 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000757}
758
Benjamin Kramer97e59492012-10-09 15:52:25 +0000759void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000760 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000761 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
762 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000763 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
764 i->DeductionFailure.Destroy();
765 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000766}
767
768void OverloadCandidateSet::clear() {
769 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000770 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000771 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000772 Functions.clear();
773}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774
John McCall4124c492011-10-17 18:40:02 +0000775namespace {
776 class UnbridgedCastsSet {
777 struct Entry {
778 Expr **Addr;
779 Expr *Saved;
780 };
781 SmallVector<Entry, 2> Entries;
782
783 public:
784 void save(Sema &S, Expr *&E) {
785 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
786 Entry entry = { &E, E };
787 Entries.push_back(entry);
788 E = S.stripARCUnbridgedCast(E);
789 }
790
791 void restore() {
792 for (SmallVectorImpl<Entry>::iterator
793 i = Entries.begin(), e = Entries.end(); i != e; ++i)
794 *i->Addr = i->Saved;
795 }
796 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000797}
John McCall4124c492011-10-17 18:40:02 +0000798
799/// checkPlaceholderForOverload - Do any interesting placeholder-like
800/// preprocessing on the given expression.
801///
802/// \param unbridgedCasts a collection to which to add unbridged casts;
803/// without this, they will be immediately diagnosed as errors
804///
805/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000806static bool
807checkPlaceholderForOverload(Sema &S, Expr *&E,
808 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000809 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
810 // We can't handle overloaded expressions here because overload
811 // resolution might reasonably tweak them.
812 if (placeholder->getKind() == BuiltinType::Overload) return false;
813
814 // If the context potentially accepts unbridged ARC casts, strip
815 // the unbridged cast and add it to the collection for later restoration.
816 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
817 unbridgedCasts) {
818 unbridgedCasts->save(S, E);
819 return false;
820 }
821
822 // Go ahead and check everything else.
823 ExprResult result = S.CheckPlaceholderExpr(E);
824 if (result.isInvalid())
825 return true;
826
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000827 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000828 return false;
829 }
830
831 // Nothing to do.
832 return false;
833}
834
835/// checkArgPlaceholdersForOverload - Check a set of call operands for
836/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000837static bool checkArgPlaceholdersForOverload(Sema &S,
838 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000839 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000840 for (unsigned i = 0, e = Args.size(); i != e; ++i)
841 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000842 return true;
843
844 return false;
845}
846
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000847// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000848// overload of the declarations in Old. This routine returns false if
849// New and Old cannot be overloaded, e.g., if New has the same
850// signature as some function in Old (C++ 1.3.10) or if the Old
851// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000852// it does return false, MatchedDecl will point to the decl that New
853// cannot be overloaded with. This decl may be a UsingShadowDecl on
854// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000855//
856// Example: Given the following input:
857//
858// void f(int, float); // #1
859// void f(int, int); // #2
860// int f(int, int); // #3
861//
862// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000863// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000864//
John McCall3d988d92009-12-02 08:47:38 +0000865// When we process #2, Old contains only the FunctionDecl for #1. By
866// comparing the parameter types, we see that #1 and #2 are overloaded
867// (since they have different signatures), so this routine returns
868// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000869//
John McCall3d988d92009-12-02 08:47:38 +0000870// When we process #3, Old is an overload set containing #1 and #2. We
871// compare the signatures of #3 to #1 (they're overloaded, so we do
872// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
873// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000874// signature), IsOverload returns false and MatchedDecl will be set to
875// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000876//
877// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
878// into a class by a using declaration. The rules for whether to hide
879// shadow declarations ignore some properties which otherwise figure
880// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000881Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000882Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
883 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000884 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000885 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000886 NamedDecl *OldD = *I;
887
888 bool OldIsUsingDecl = false;
889 if (isa<UsingShadowDecl>(OldD)) {
890 OldIsUsingDecl = true;
891
892 // We can always introduce two using declarations into the same
893 // context, even if they have identical signatures.
894 if (NewIsUsingDecl) continue;
895
896 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
897 }
898
899 // If either declaration was introduced by a using declaration,
900 // we'll need to use slightly different rules for matching.
901 // Essentially, these rules are the normal rules, except that
902 // function templates hide function templates with different
903 // return types or template parameter lists.
904 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000905 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
906 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000907
Alp Tokera2794f92014-01-22 07:29:52 +0000908 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000909 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
910 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
911 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
912 continue;
913 }
914
Alp Tokera2794f92014-01-22 07:29:52 +0000915 if (!isa<FunctionTemplateDecl>(OldD) &&
916 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000917 continue;
918
John McCalldaa3d6b2009-12-09 03:35:25 +0000919 Match = *I;
920 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000921 }
John McCalla8987a2942010-11-10 03:01:53 +0000922 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000923 // We can overload with these, which can show up when doing
924 // redeclaration checks for UsingDecls.
925 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000926 } else if (isa<TagDecl>(OldD)) {
927 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000928 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
929 // Optimistically assume that an unresolved using decl will
930 // overload; if it doesn't, we'll have to diagnose during
931 // template instantiation.
932 } else {
John McCall1f82f242009-11-18 22:49:29 +0000933 // (C++ 13p1):
934 // Only function declarations can be overloaded; object and type
935 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000936 Match = *I;
937 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000938 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000939 }
John McCall1f82f242009-11-18 22:49:29 +0000940
John McCalldaa3d6b2009-12-09 03:35:25 +0000941 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000942}
943
Richard Smithac974a32013-06-30 09:48:50 +0000944bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
945 bool UseUsingDeclRules) {
946 // C++ [basic.start.main]p2: This function shall not be overloaded.
947 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000948 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000949
David Majnemerc729b0b2013-09-16 22:44:20 +0000950 // MSVCRT user defined entry points cannot be overloaded.
951 if (New->isMSVCRTEntryPoint())
952 return false;
953
John McCall1f82f242009-11-18 22:49:29 +0000954 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
955 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
956
957 // C++ [temp.fct]p2:
958 // A function template can be overloaded with other function templates
959 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +0000960 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +0000961 return true;
962
963 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000964 QualType OldQType = Context.getCanonicalType(Old->getType());
965 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000966
967 // Compare the signatures (C++ 1.3.10) of the two functions to
968 // determine whether they are overloads. If we find any mismatch
969 // in the signature, they are overloads.
970
971 // If either of these functions is a K&R-style function (no
972 // prototype), then we consider them to have matching signatures.
973 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
974 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
975 return false;
976
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000977 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
978 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000979
980 // The signature of a function includes the types of its
981 // parameters (C++ 1.3.10), which includes the presence or absence
982 // of the ellipsis; see C++ DR 357).
983 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +0000984 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +0000985 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000986 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000987 return true;
988
989 // C++ [temp.over.link]p4:
990 // The signature of a function template consists of its function
991 // signature, its return type and its template parameter list. The names
992 // of the template parameters are significant only for establishing the
993 // relationship between the template parameters and the rest of the
994 // signature.
995 //
996 // We check the return type and template parameter lists for function
997 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000998 //
999 // However, we don't consider either of these when deciding whether
1000 // a member introduced by a shadow declaration is hidden.
1001 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001002 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1003 OldTemplate->getTemplateParameters(),
1004 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001005 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001006 return true;
1007
1008 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001009 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001010 //
1011 // As part of this, also check whether one of the member functions
1012 // is static, in which case they are not overloads (C++
1013 // 13.1p2). While not part of the definition of the signature,
1014 // this check is important to determine whether these functions
1015 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001016 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1017 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001018 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001019 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1020 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1021 if (!UseUsingDeclRules &&
1022 (OldMethod->getRefQualifier() == RQ_None ||
1023 NewMethod->getRefQualifier() == RQ_None)) {
1024 // C++0x [over.load]p2:
1025 // - Member function declarations with the same name and the same
1026 // parameter-type-list as well as member function template
1027 // declarations with the same name, the same parameter-type-list, and
1028 // the same template parameter lists cannot be overloaded if any of
1029 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001030 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001031 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001032 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001033 }
1034 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001035 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036
Richard Smith574f4f62013-01-14 05:37:29 +00001037 // We may not have applied the implicit const for a constexpr member
1038 // function yet (because we haven't yet resolved whether this is a static
1039 // or non-static member function). Add it now, on the assumption that this
1040 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001041 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001042 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001043 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001044 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001045 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001046
1047 // We do not allow overloading based off of '__restrict'.
1048 OldQuals &= ~Qualifiers::Restrict;
1049 NewQuals &= ~Qualifiers::Restrict;
1050 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001051 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001052 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001053
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001054 // enable_if attributes are an order-sensitive part of the signature.
1055 for (specific_attr_iterator<EnableIfAttr>
1056 NewI = New->specific_attr_begin<EnableIfAttr>(),
1057 NewE = New->specific_attr_end<EnableIfAttr>(),
1058 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1059 OldE = Old->specific_attr_end<EnableIfAttr>();
1060 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1061 if (NewI == NewE || OldI == OldE)
1062 return true;
1063 llvm::FoldingSetNodeID NewID, OldID;
1064 NewI->getCond()->Profile(NewID, Context, true);
1065 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001066 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001067 return true;
1068 }
1069
John McCall1f82f242009-11-18 22:49:29 +00001070 // The signatures match; this is not an overload.
1071 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001072}
1073
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001074/// \brief Checks availability of the function depending on the current
1075/// function context. Inside an unavailable function, unavailability is ignored.
1076///
1077/// \returns true if \arg FD is unavailable and current context is inside
1078/// an available function, false otherwise.
1079bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1080 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1081}
1082
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001083/// \brief Tries a user-defined conversion from From to ToType.
1084///
1085/// Produces an implicit conversion sequence for when a standard conversion
1086/// is not an option. See TryImplicitConversion for more information.
1087static ImplicitConversionSequence
1088TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1089 bool SuppressUserConversions,
1090 bool AllowExplicit,
1091 bool InOverloadResolution,
1092 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001093 bool AllowObjCWritebackConversion,
1094 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001095 ImplicitConversionSequence ICS;
1096
1097 if (SuppressUserConversions) {
1098 // We're not in the case above, so there is no conversion that
1099 // we can perform.
1100 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1101 return ICS;
1102 }
1103
1104 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001105 OverloadCandidateSet Conversions(From->getExprLoc(),
1106 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001107 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1108 Conversions, AllowExplicit,
1109 AllowObjCConversionOnExplicit)) {
1110 case OR_Success:
1111 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001112 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001113 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001114 // C++ [over.ics.user]p4:
1115 // A conversion of an expression of class type to the same class
1116 // type is given Exact Match rank, and a conversion of an
1117 // expression of class type to a base class of that type is
1118 // given Conversion rank, in spite of the fact that a copy
1119 // constructor (i.e., a user-defined conversion function) is
1120 // called for those cases.
1121 if (CXXConstructorDecl *Constructor
1122 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1123 QualType FromCanon
1124 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1125 QualType ToCanon
1126 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1127 if (Constructor->isCopyConstructor() &&
1128 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1129 // Turn this into a "standard" conversion sequence, so that it
1130 // gets ranked with standard conversion sequences.
1131 ICS.setStandard();
1132 ICS.Standard.setAsIdentityConversion();
1133 ICS.Standard.setFromType(From->getType());
1134 ICS.Standard.setAllToTypes(ToType);
1135 ICS.Standard.CopyConstructor = Constructor;
1136 if (ToCanon != FromCanon)
1137 ICS.Standard.Second = ICK_Derived_To_Base;
1138 }
1139 }
Richard Smith48372b62015-01-27 03:30:40 +00001140 break;
1141
1142 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001143 ICS.setAmbiguous();
1144 ICS.Ambiguous.setFromType(From->getType());
1145 ICS.Ambiguous.setToType(ToType);
1146 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1147 Cand != Conversions.end(); ++Cand)
1148 if (Cand->Viable)
1149 ICS.Ambiguous.addConversion(Cand->Function);
1150 break;
Richard Smith48372b62015-01-27 03:30:40 +00001151
1152 // Fall through.
1153 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001154 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001155 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001156 }
1157
1158 return ICS;
1159}
1160
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001161/// TryImplicitConversion - Attempt to perform an implicit conversion
1162/// from the given expression (Expr) to the given type (ToType). This
1163/// function returns an implicit conversion sequence that can be used
1164/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001165///
1166/// void f(float f);
1167/// void g(int i) { f(i); }
1168///
1169/// this routine would produce an implicit conversion sequence to
1170/// describe the initialization of f from i, which will be a standard
1171/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1172/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1173//
1174/// Note that this routine only determines how the conversion can be
1175/// performed; it does not actually perform the conversion. As such,
1176/// it will not produce any diagnostics if no conversion is available,
1177/// but will instead return an implicit conversion sequence of kind
1178/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001179///
1180/// If @p SuppressUserConversions, then user-defined conversions are
1181/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001182/// If @p AllowExplicit, then explicit user-defined conversions are
1183/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001184///
1185/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1186/// writeback conversion, which allows __autoreleasing id* parameters to
1187/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001188static ImplicitConversionSequence
1189TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1190 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001191 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001192 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001193 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001194 bool AllowObjCWritebackConversion,
1195 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001196 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001197 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001198 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001199 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001200 return ICS;
1201 }
1202
David Blaikiebbafb8a2012-03-11 07:00:24 +00001203 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001204 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001205 return ICS;
1206 }
1207
Douglas Gregor836a7e82010-08-11 02:15:33 +00001208 // C++ [over.ics.user]p4:
1209 // A conversion of an expression of class type to the same class
1210 // type is given Exact Match rank, and a conversion of an
1211 // expression of class type to a base class of that type is
1212 // given Conversion rank, in spite of the fact that a copy/move
1213 // constructor (i.e., a user-defined conversion function) is
1214 // called for those cases.
1215 QualType FromType = From->getType();
1216 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001217 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1218 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001219 ICS.setStandard();
1220 ICS.Standard.setAsIdentityConversion();
1221 ICS.Standard.setFromType(FromType);
1222 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001223
Douglas Gregor5ab11652010-04-17 22:01:05 +00001224 // We don't actually check at this point whether there is a valid
1225 // copy/move constructor, since overloading just assumes that it
1226 // exists. When we actually perform initialization, we'll find the
1227 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001228 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001229
Douglas Gregor5ab11652010-04-17 22:01:05 +00001230 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001231 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001232 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001233
Douglas Gregor836a7e82010-08-11 02:15:33 +00001234 return ICS;
1235 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001237 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1238 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001239 AllowObjCWritebackConversion,
1240 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001241}
1242
John McCall31168b02011-06-15 23:02:42 +00001243ImplicitConversionSequence
1244Sema::TryImplicitConversion(Expr *From, QualType ToType,
1245 bool SuppressUserConversions,
1246 bool AllowExplicit,
1247 bool InOverloadResolution,
1248 bool CStyle,
1249 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001250 return ::TryImplicitConversion(*this, From, ToType,
1251 SuppressUserConversions, AllowExplicit,
1252 InOverloadResolution, CStyle,
1253 AllowObjCWritebackConversion,
1254 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001255}
1256
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001257/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001258/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001259/// converted expression. Flavor is the kind of conversion we're
1260/// performing, used in the error message. If @p AllowExplicit,
1261/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001262ExprResult
1263Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001264 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001265 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001266 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001267}
1268
John Wiegley01296292011-04-08 18:41:53 +00001269ExprResult
1270Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001271 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001272 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001273 if (checkPlaceholderForOverload(*this, From))
1274 return ExprError();
1275
John McCall31168b02011-06-15 23:02:42 +00001276 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1277 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001278 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001279 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001280 if (getLangOpts().ObjC1)
1281 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1282 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001283 ICS = ::TryImplicitConversion(*this, From, ToType,
1284 /*SuppressUserConversions=*/false,
1285 AllowExplicit,
1286 /*InOverloadResolution=*/false,
1287 /*CStyle=*/false,
1288 AllowObjCWritebackConversion,
1289 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001290 return PerformImplicitConversion(From, ToType, ICS, Action);
1291}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001292
1293/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001294/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001295bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1296 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001297 if (Context.hasSameUnqualifiedType(FromType, ToType))
1298 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001299
John McCall991eb4b2010-12-21 00:44:39 +00001300 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1301 // where F adds one of the following at most once:
1302 // - a pointer
1303 // - a member pointer
1304 // - a block pointer
1305 CanQualType CanTo = Context.getCanonicalType(ToType);
1306 CanQualType CanFrom = Context.getCanonicalType(FromType);
1307 Type::TypeClass TyClass = CanTo->getTypeClass();
1308 if (TyClass != CanFrom->getTypeClass()) return false;
1309 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1310 if (TyClass == Type::Pointer) {
1311 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1312 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1313 } else if (TyClass == Type::BlockPointer) {
1314 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1315 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1316 } else if (TyClass == Type::MemberPointer) {
1317 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1318 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1319 } else {
1320 return false;
1321 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001322
John McCall991eb4b2010-12-21 00:44:39 +00001323 TyClass = CanTo->getTypeClass();
1324 if (TyClass != CanFrom->getTypeClass()) return false;
1325 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1326 return false;
1327 }
1328
1329 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1330 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1331 if (!EInfo.getNoReturn()) return false;
1332
1333 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1334 assert(QualType(FromFn, 0).isCanonical());
1335 if (QualType(FromFn, 0) != CanTo) return false;
1336
1337 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001338 return true;
1339}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001340
Douglas Gregor46188682010-05-18 22:42:18 +00001341/// \brief Determine whether the conversion from FromType to ToType is a valid
1342/// vector conversion.
1343///
1344/// \param ICK Will be set to the vector conversion kind, if this is a vector
1345/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001346static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001347 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001348 // We need at least one of these types to be a vector type to have a vector
1349 // conversion.
1350 if (!ToType->isVectorType() && !FromType->isVectorType())
1351 return false;
1352
1353 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001354 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001355 return false;
1356
1357 // There are no conversions between extended vector types, only identity.
1358 if (ToType->isExtVectorType()) {
1359 // There are no conversions between extended vector types other than the
1360 // identity conversion.
1361 if (FromType->isExtVectorType())
1362 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363
Douglas Gregor46188682010-05-18 22:42:18 +00001364 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001365 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001366 ICK = ICK_Vector_Splat;
1367 return true;
1368 }
1369 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001370
1371 // We can perform the conversion between vector types in the following cases:
1372 // 1)vector types are equivalent AltiVec and GCC vector types
1373 // 2)lax vector conversions are permitted and the vector types are of the
1374 // same size
1375 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001376 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1377 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001378 ICK = ICK_Vector_Conversion;
1379 return true;
1380 }
Douglas Gregor46188682010-05-18 22:42:18 +00001381 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001382
Douglas Gregor46188682010-05-18 22:42:18 +00001383 return false;
1384}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001385
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001386static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1387 bool InOverloadResolution,
1388 StandardConversionSequence &SCS,
1389 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001390
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001391/// IsStandardConversion - Determines whether there is a standard
1392/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1393/// expression From to the type ToType. Standard conversion sequences
1394/// only consider non-class types; for conversions that involve class
1395/// types, use TryImplicitConversion. If a conversion exists, SCS will
1396/// contain the standard conversion sequence required to perform this
1397/// conversion and this routine will return true. Otherwise, this
1398/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001399static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1400 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001401 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001402 bool CStyle,
1403 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001404 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001405
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001406 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001407 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001408 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001409 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001410 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001411
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001412 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001413 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001414 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001415 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001416 return false;
1417
Mike Stump11289f42009-09-09 15:08:12 +00001418 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001419 }
1420
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001421 // The first conversion can be an lvalue-to-rvalue conversion,
1422 // array-to-pointer conversion, or function-to-pointer conversion
1423 // (C++ 4p1).
1424
John McCall5c32be02010-08-24 20:38:10 +00001425 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001426 DeclAccessPair AccessPair;
1427 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001428 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001429 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001430 // We were able to resolve the address of the overloaded function,
1431 // so we can convert to the type of that function.
1432 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001433 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001434
1435 // we can sometimes resolve &foo<int> regardless of ToType, so check
1436 // if the type matches (identity) or we are converting to bool
1437 if (!S.Context.hasSameUnqualifiedType(
1438 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1439 QualType resultTy;
1440 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001441 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001442 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1443 // otherwise, only a boolean conversion is standard
1444 if (!ToType->isBooleanType())
1445 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001447
Chandler Carruthffce2452011-03-29 08:08:18 +00001448 // Check if the "from" expression is taking the address of an overloaded
1449 // function and recompute the FromType accordingly. Take advantage of the
1450 // fact that non-static member functions *must* have such an address-of
1451 // expression.
1452 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1453 if (Method && !Method->isStatic()) {
1454 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1455 "Non-unary operator on non-static member address");
1456 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1457 == UO_AddrOf &&
1458 "Non-address-of operator on non-static member address");
1459 const Type *ClassType
1460 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1461 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001462 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1463 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1464 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001465 "Non-address-of operator for overloaded function expression");
1466 FromType = S.Context.getPointerType(FromType);
1467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468
Douglas Gregor980fb162010-04-29 18:24:40 +00001469 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001470 assert(S.Context.hasSameType(
1471 FromType,
1472 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001473 } else {
1474 return false;
1475 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001476 }
John McCall154a2fd2011-08-30 00:57:29 +00001477 // Lvalue-to-rvalue conversion (C++11 4.1):
1478 // A glvalue (3.10) of a non-function, non-array type T can
1479 // be converted to a prvalue.
1480 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001481 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001482 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001483 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001484 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001485
Douglas Gregorc79862f2012-04-12 17:51:55 +00001486 // C11 6.3.2.1p2:
1487 // ... if the lvalue has atomic type, the value has the non-atomic version
1488 // of the type of the lvalue ...
1489 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1490 FromType = Atomic->getValueType();
1491
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001492 // If T is a non-class type, the type of the rvalue is the
1493 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001494 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1495 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001496 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001497 } else if (FromType->isArrayType()) {
1498 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001499 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001500
1501 // An lvalue or rvalue of type "array of N T" or "array of unknown
1502 // bound of T" can be converted to an rvalue of type "pointer to
1503 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001504 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001505
John McCall5c32be02010-08-24 20:38:10 +00001506 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001507 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001508 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001509
1510 // For the purpose of ranking in overload resolution
1511 // (13.3.3.1.1), this conversion is considered an
1512 // array-to-pointer conversion followed by a qualification
1513 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001514 SCS.Second = ICK_Identity;
1515 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001516 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001517 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001518 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001519 }
John McCall086a4642010-11-24 05:12:34 +00001520 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001521 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001522 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001523
1524 // An lvalue of function type T can be converted to an rvalue of
1525 // type "pointer to T." The result is a pointer to the
1526 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001527 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001528 } else {
1529 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001530 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001532 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001533
1534 // The second conversion can be an integral promotion, floating
1535 // point promotion, integral conversion, floating point conversion,
1536 // floating-integral conversion, pointer conversion,
1537 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001538 // For overloading in C, this can also be a "compatible-type"
1539 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001540 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001541 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001542 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001543 // The unqualified versions of the types are the same: there's no
1544 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001545 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001546 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001547 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001548 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001549 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001550 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001551 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001552 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001553 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001554 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001555 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001556 SCS.Second = ICK_Complex_Promotion;
1557 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001558 } else if (ToType->isBooleanType() &&
1559 (FromType->isArithmeticType() ||
1560 FromType->isAnyPointerType() ||
1561 FromType->isBlockPointerType() ||
1562 FromType->isMemberPointerType() ||
1563 FromType->isNullPtrType())) {
1564 // Boolean conversions (C++ 4.12).
1565 SCS.Second = ICK_Boolean_Conversion;
1566 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001567 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001568 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001569 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001570 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001571 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001572 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001573 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001574 SCS.Second = ICK_Complex_Conversion;
1575 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001576 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1577 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001578 // Complex-real conversions (C99 6.3.1.7)
1579 SCS.Second = ICK_Complex_Real;
1580 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001581 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001582 // Floating point conversions (C++ 4.8).
1583 SCS.Second = ICK_Floating_Conversion;
1584 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001585 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001586 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001587 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001588 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001589 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001590 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001591 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001592 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001593 SCS.Second = ICK_Block_Pointer_Conversion;
1594 } else if (AllowObjCWritebackConversion &&
1595 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1596 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001597 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1598 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001599 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001600 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001601 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001602 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001603 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001604 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001605 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001606 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001607 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001608 SCS.Second = SecondICK;
1609 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001610 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001611 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001612 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001613 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001614 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001615 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001616 // Treat a conversion that strips "noreturn" as an identity conversion.
1617 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001618 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1619 InOverloadResolution,
1620 SCS, CStyle)) {
1621 SCS.Second = ICK_TransparentUnionConversion;
1622 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001623 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1624 CStyle)) {
1625 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001626 // appropriately.
1627 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001628 } else if (ToType->isEventT() &&
1629 From->isIntegerConstantExpr(S.getASTContext()) &&
1630 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1631 SCS.Second = ICK_Zero_Event_Conversion;
1632 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001633 } else {
1634 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001635 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001636 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001637 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001639 QualType CanonFrom;
1640 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001641 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001642 bool ObjCLifetimeConversion;
1643 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1644 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001645 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001646 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001647 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001648 CanonFrom = S.Context.getCanonicalType(FromType);
1649 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001650 } else {
1651 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001652 SCS.Third = ICK_Identity;
1653
Mike Stump11289f42009-09-09 15:08:12 +00001654 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001655 // [...] Any difference in top-level cv-qualification is
1656 // subsumed by the initialization itself and does not constitute
1657 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001658 CanonFrom = S.Context.getCanonicalType(FromType);
1659 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001660 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001661 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001662 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001663 FromType = ToType;
1664 CanonFrom = CanonTo;
1665 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001666 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001667 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001668
1669 // If we have not converted the argument type to the parameter type,
1670 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001671 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001672 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001673
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001674 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001676
1677static bool
1678IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1679 QualType &ToType,
1680 bool InOverloadResolution,
1681 StandardConversionSequence &SCS,
1682 bool CStyle) {
1683
1684 const RecordType *UT = ToType->getAsUnionType();
1685 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1686 return false;
1687 // The field to initialize within the transparent union.
1688 RecordDecl *UD = UT->getDecl();
1689 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001690 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001691 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1692 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001693 ToType = it->getType();
1694 return true;
1695 }
1696 }
1697 return false;
1698}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001699
1700/// IsIntegralPromotion - Determines whether the conversion from the
1701/// expression From (whose potentially-adjusted type is FromType) to
1702/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1703/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001704bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001705 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001706 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001707 if (!To) {
1708 return false;
1709 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001710
1711 // An rvalue of type char, signed char, unsigned char, short int, or
1712 // unsigned short int can be converted to an rvalue of type int if
1713 // int can represent all the values of the source type; otherwise,
1714 // the source rvalue can be converted to an rvalue of type unsigned
1715 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001716 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1717 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718 if (// We can promote any signed, promotable integer type to an int
1719 (FromType->isSignedIntegerType() ||
1720 // We can promote any unsigned integer type whose size is
1721 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001722 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001723 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001724 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001725 }
1726
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001727 return To->getKind() == BuiltinType::UInt;
1728 }
1729
Richard Smithb9c5a602012-09-13 21:18:54 +00001730 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001731 // A prvalue of an unscoped enumeration type whose underlying type is not
1732 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1733 // following types that can represent all the values of the enumeration
1734 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1735 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001736 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001737 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001738 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001739 // with lowest integer conversion rank (4.13) greater than the rank of long
1740 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001741 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001742 // C++11 [conv.prom]p4:
1743 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1744 // can be converted to a prvalue of its underlying type. Moreover, if
1745 // integral promotion can be applied to its underlying type, a prvalue of an
1746 // unscoped enumeration type whose underlying type is fixed can also be
1747 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001748 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1749 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1750 // provided for a scoped enumeration.
1751 if (FromEnumType->getDecl()->isScoped())
1752 return false;
1753
Richard Smithb9c5a602012-09-13 21:18:54 +00001754 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001755 // even if that's not the promoted type. Note that the check for promoting
1756 // the underlying type is based on the type alone, and does not consider
1757 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001758 if (FromEnumType->getDecl()->isFixed()) {
1759 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1760 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001761 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001762 }
1763
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001764 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001765 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001766 !RequireCompleteType(From->getLocStart(), FromType, 0))
Richard Smith88f4bba2015-03-26 00:16:07 +00001767 return Context.hasSameUnqualifiedType(
1768 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001769 }
John McCall56774992009-12-09 09:09:27 +00001770
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001771 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001772 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1773 // to an rvalue a prvalue of the first of the following types that can
1774 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001775 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001776 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001777 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001778 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001779 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001780 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001781 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001782 // Determine whether the type we're converting from is signed or
1783 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001784 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001785 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001786
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001787 // The types we'll try to promote to, in the appropriate
1788 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001789 QualType PromoteTypes[6] = {
1790 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001791 Context.LongTy, Context.UnsignedLongTy ,
1792 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001793 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001794 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001795 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1796 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001797 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001798 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1799 // We found the type that we can promote to. If this is the
1800 // type we wanted, we have a promotion. Otherwise, no
1801 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001802 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001803 }
1804 }
1805 }
1806
1807 // An rvalue for an integral bit-field (9.6) can be converted to an
1808 // rvalue of type int if int can represent all the values of the
1809 // bit-field; otherwise, it can be converted to unsigned int if
1810 // unsigned int can represent all the values of the bit-field. If
1811 // the bit-field is larger yet, no integral promotion applies to
1812 // it. If the bit-field has an enumerated type, it is treated as any
1813 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001814 // FIXME: We should delay checking of bit-fields until we actually perform the
1815 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001816 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001817 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001818 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001819 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001820 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001821 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001822 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001823
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001824 // Are we promoting to an int from a bitfield that fits in an int?
1825 if (BitWidth < ToSize ||
1826 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1827 return To->getKind() == BuiltinType::Int;
1828 }
Mike Stump11289f42009-09-09 15:08:12 +00001829
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001830 // Are we promoting to an unsigned int from an unsigned bitfield
1831 // that fits into an unsigned int?
1832 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1833 return To->getKind() == BuiltinType::UInt;
1834 }
Mike Stump11289f42009-09-09 15:08:12 +00001835
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001836 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001837 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001838 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001839 }
Mike Stump11289f42009-09-09 15:08:12 +00001840
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001841 // An rvalue of type bool can be converted to an rvalue of type int,
1842 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001843 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001844 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001845 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001846
1847 return false;
1848}
1849
1850/// IsFloatingPointPromotion - Determines whether the conversion from
1851/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1852/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001853bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001854 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1855 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001856 /// An rvalue of type float can be converted to an rvalue of type
1857 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001858 if (FromBuiltin->getKind() == BuiltinType::Float &&
1859 ToBuiltin->getKind() == BuiltinType::Double)
1860 return true;
1861
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001862 // C99 6.3.1.5p1:
1863 // When a float is promoted to double or long double, or a
1864 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001865 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001866 (FromBuiltin->getKind() == BuiltinType::Float ||
1867 FromBuiltin->getKind() == BuiltinType::Double) &&
1868 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1869 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001870
1871 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001872 if (!getLangOpts().NativeHalfType &&
1873 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001874 ToBuiltin->getKind() == BuiltinType::Float)
1875 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001876 }
1877
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001878 return false;
1879}
1880
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001881/// \brief Determine if a conversion is a complex promotion.
1882///
1883/// A complex promotion is defined as a complex -> complex conversion
1884/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001885/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001886bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001887 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001888 if (!FromComplex)
1889 return false;
1890
John McCall9dd450b2009-09-21 23:43:11 +00001891 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001892 if (!ToComplex)
1893 return false;
1894
1895 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001896 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001897 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001898 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001899}
1900
Douglas Gregor237f96c2008-11-26 23:31:11 +00001901/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1902/// the pointer type FromPtr to a pointer to type ToPointee, with the
1903/// same type qualifiers as FromPtr has on its pointee type. ToType,
1904/// if non-empty, will be a pointer to ToType that may or may not have
1905/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001906///
Mike Stump11289f42009-09-09 15:08:12 +00001907static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001908BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001909 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001910 ASTContext &Context,
1911 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001912 assert((FromPtr->getTypeClass() == Type::Pointer ||
1913 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1914 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001915
John McCall31168b02011-06-15 23:02:42 +00001916 /// Conversions to 'id' subsume cv-qualifier conversions.
1917 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001918 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919
1920 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001921 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001922 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001923 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001924
John McCall31168b02011-06-15 23:02:42 +00001925 if (StripObjCLifetime)
1926 Quals.removeObjCLifetime();
1927
Mike Stump11289f42009-09-09 15:08:12 +00001928 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001929 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001930 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001931 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001932 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001933
1934 // Build a pointer to ToPointee. It has the right qualifiers
1935 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001936 if (isa<ObjCObjectPointerType>(ToType))
1937 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001938 return Context.getPointerType(ToPointee);
1939 }
1940
1941 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001942 QualType QualifiedCanonToPointee
1943 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001944
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001945 if (isa<ObjCObjectPointerType>(ToType))
1946 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1947 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001948}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001949
Mike Stump11289f42009-09-09 15:08:12 +00001950static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001951 bool InOverloadResolution,
1952 ASTContext &Context) {
1953 // Handle value-dependent integral null pointer constants correctly.
1954 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1955 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001956 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001957 return !InOverloadResolution;
1958
Douglas Gregor56751b52009-09-25 04:25:58 +00001959 return Expr->isNullPointerConstant(Context,
1960 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1961 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001962}
Mike Stump11289f42009-09-09 15:08:12 +00001963
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001964/// IsPointerConversion - Determines whether the conversion of the
1965/// expression From, which has the (possibly adjusted) type FromType,
1966/// can be converted to the type ToType via a pointer conversion (C++
1967/// 4.10). If so, returns true and places the converted type (that
1968/// might differ from ToType in its cv-qualifiers at some level) into
1969/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001970///
Douglas Gregora29dc052008-11-27 01:19:21 +00001971/// This routine also supports conversions to and from block pointers
1972/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1973/// pointers to interfaces. FIXME: Once we've determined the
1974/// appropriate overloading rules for Objective-C, we may want to
1975/// split the Objective-C checks into a different routine; however,
1976/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001977/// conversions, so for now they live here. IncompatibleObjC will be
1978/// set if the conversion is an allowed Objective-C conversion that
1979/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001980bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001981 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001982 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001983 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001984 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001985 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1986 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001987 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001988
Mike Stump11289f42009-09-09 15:08:12 +00001989 // Conversion from a null pointer constant to any Objective-C pointer type.
1990 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001991 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001992 ConvertedType = ToType;
1993 return true;
1994 }
1995
Douglas Gregor231d1c62008-11-27 00:15:41 +00001996 // Blocks: Block pointers can be converted to void*.
1997 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001998 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001999 ConvertedType = ToType;
2000 return true;
2001 }
2002 // Blocks: A null pointer constant can be converted to a block
2003 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002004 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002005 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002006 ConvertedType = ToType;
2007 return true;
2008 }
2009
Sebastian Redl576fd422009-05-10 18:38:11 +00002010 // If the left-hand-side is nullptr_t, the right side can be a null
2011 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002012 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002014 ConvertedType = ToType;
2015 return true;
2016 }
2017
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002018 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002019 if (!ToTypePtr)
2020 return false;
2021
2022 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002023 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002024 ConvertedType = ToType;
2025 return true;
2026 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002027
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002029 // , including objective-c pointers.
2030 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002031 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002032 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002033 ConvertedType = BuildSimilarlyQualifiedPointerType(
2034 FromType->getAs<ObjCObjectPointerType>(),
2035 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002036 ToType, Context);
2037 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002038 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002039 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002040 if (!FromTypePtr)
2041 return false;
2042
2043 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002044
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002045 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002046 // pointer conversion, so don't do all of the work below.
2047 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2048 return false;
2049
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002050 // An rvalue of type "pointer to cv T," where T is an object type,
2051 // can be converted to an rvalue of type "pointer to cv void" (C++
2052 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002053 if (FromPointeeType->isIncompleteOrObjectType() &&
2054 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002055 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002056 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002057 ToType, Context,
2058 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002059 return true;
2060 }
2061
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002062 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002063 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002064 ToPointeeType->isVoidType()) {
2065 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2066 ToPointeeType,
2067 ToType, Context);
2068 return true;
2069 }
2070
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002071 // When we're overloading in C, we allow a special kind of pointer
2072 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002073 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002074 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002075 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002076 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002077 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002078 return true;
2079 }
2080
Douglas Gregor5c407d92008-10-23 00:40:37 +00002081 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002082 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002083 // An rvalue of type "pointer to cv D," where D is a class type,
2084 // can be converted to an rvalue of type "pointer to cv B," where
2085 // B is a base class (clause 10) of D. If B is an inaccessible
2086 // (clause 11) or ambiguous (10.2) base class of D, a program that
2087 // necessitates this conversion is ill-formed. The result of the
2088 // conversion is a pointer to the base class sub-object of the
2089 // derived class object. The null pointer value is converted to
2090 // the null pointer value of the destination type.
2091 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002092 // Note that we do not check for ambiguity or inaccessibility
2093 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002094 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002095 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002096 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002097 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002098 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002100 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002101 ToType, Context);
2102 return true;
2103 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002104
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002105 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2106 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2107 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2108 ToPointeeType,
2109 ToType, Context);
2110 return true;
2111 }
2112
Douglas Gregora119f102008-12-19 19:13:09 +00002113 return false;
2114}
Douglas Gregoraec25842011-04-26 23:16:46 +00002115
2116/// \brief Adopt the given qualifiers for the given type.
2117static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2118 Qualifiers TQs = T.getQualifiers();
2119
2120 // Check whether qualifiers already match.
2121 if (TQs == Qs)
2122 return T;
2123
2124 if (Qs.compatiblyIncludes(TQs))
2125 return Context.getQualifiedType(T, Qs);
2126
2127 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2128}
Douglas Gregora119f102008-12-19 19:13:09 +00002129
2130/// isObjCPointerConversion - Determines whether this is an
2131/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2132/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002133bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002134 QualType& ConvertedType,
2135 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002136 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002137 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002138
Douglas Gregoraec25842011-04-26 23:16:46 +00002139 // The set of qualifiers on the type we're converting from.
2140 Qualifiers FromQualifiers = FromType.getQualifiers();
2141
Steve Naroff7cae42b2009-07-10 23:34:53 +00002142 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002143 const ObjCObjectPointerType* ToObjCPtr =
2144 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002145 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002146 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002147
Steve Naroff7cae42b2009-07-10 23:34:53 +00002148 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002149 // If the pointee types are the same (ignoring qualifications),
2150 // then this is not a pointer conversion.
2151 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2152 FromObjCPtr->getPointeeType()))
2153 return false;
2154
Douglas Gregorab209d82015-07-07 03:58:42 +00002155 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002156 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002157 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2158 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002159 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002160 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2161 FromObjCPtr->getPointeeType()))
2162 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002163 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002164 ToObjCPtr->getPointeeType(),
2165 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002166 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002167 return true;
2168 }
2169
2170 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2171 // Okay: this is some kind of implicit downcast of Objective-C
2172 // interfaces, which is permitted. However, we're going to
2173 // complain about it.
2174 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002175 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002176 ToObjCPtr->getPointeeType(),
2177 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002178 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002179 return true;
2180 }
Mike Stump11289f42009-09-09 15:08:12 +00002181 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002182 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002183 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002184 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002185 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002186 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002187 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002188 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002189 // to a block pointer type.
2190 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002191 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002192 return true;
2193 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002194 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002195 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002196 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002197 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002198 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002199 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002200 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002201 return true;
2202 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002203 else
Douglas Gregora119f102008-12-19 19:13:09 +00002204 return false;
2205
Douglas Gregor033f56d2008-12-23 00:53:59 +00002206 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002207 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002208 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002209 else if (const BlockPointerType *FromBlockPtr =
2210 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002211 FromPointeeType = FromBlockPtr->getPointeeType();
2212 else
Douglas Gregora119f102008-12-19 19:13:09 +00002213 return false;
2214
Douglas Gregora119f102008-12-19 19:13:09 +00002215 // If we have pointers to pointers, recursively check whether this
2216 // is an Objective-C conversion.
2217 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2218 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2219 IncompatibleObjC)) {
2220 // We always complain about this conversion.
2221 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002222 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002223 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002224 return true;
2225 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002226 // Allow conversion of pointee being objective-c pointer to another one;
2227 // as in I* to id.
2228 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2229 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2230 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2231 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002232
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002233 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002234 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002235 return true;
2236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002237
Douglas Gregor033f56d2008-12-23 00:53:59 +00002238 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002239 // differences in the argument and result types are in Objective-C
2240 // pointer conversions. If so, we permit the conversion (but
2241 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002242 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002243 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002244 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002245 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002246 if (FromFunctionType && ToFunctionType) {
2247 // If the function types are exactly the same, this isn't an
2248 // Objective-C pointer conversion.
2249 if (Context.getCanonicalType(FromPointeeType)
2250 == Context.getCanonicalType(ToPointeeType))
2251 return false;
2252
2253 // Perform the quick checks that will tell us whether these
2254 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002255 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002256 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2257 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2258 return false;
2259
2260 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002261 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2262 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002263 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002264 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2265 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002266 ConvertedType, IncompatibleObjC)) {
2267 // Okay, we have an Objective-C pointer conversion.
2268 HasObjCConversion = true;
2269 } else {
2270 // Function types are too different. Abort.
2271 return false;
2272 }
Mike Stump11289f42009-09-09 15:08:12 +00002273
Douglas Gregora119f102008-12-19 19:13:09 +00002274 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002275 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002276 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002277 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2278 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002279 if (Context.getCanonicalType(FromArgType)
2280 == Context.getCanonicalType(ToArgType)) {
2281 // Okay, the types match exactly. Nothing to do.
2282 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2283 ConvertedType, IncompatibleObjC)) {
2284 // Okay, we have an Objective-C pointer conversion.
2285 HasObjCConversion = true;
2286 } else {
2287 // Argument types are too different. Abort.
2288 return false;
2289 }
2290 }
2291
2292 if (HasObjCConversion) {
2293 // We had an Objective-C conversion. Allow this pointer
2294 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002295 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002296 IncompatibleObjC = true;
2297 return true;
2298 }
2299 }
2300
Sebastian Redl72b597d2009-01-25 19:43:20 +00002301 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002302}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002303
John McCall31168b02011-06-15 23:02:42 +00002304/// \brief Determine whether this is an Objective-C writeback conversion,
2305/// used for parameter passing when performing automatic reference counting.
2306///
2307/// \param FromType The type we're converting form.
2308///
2309/// \param ToType The type we're converting to.
2310///
2311/// \param ConvertedType The type that will be produced after applying
2312/// this conversion.
2313bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2314 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002315 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002316 Context.hasSameUnqualifiedType(FromType, ToType))
2317 return false;
2318
2319 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2320 QualType ToPointee;
2321 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2322 ToPointee = ToPointer->getPointeeType();
2323 else
2324 return false;
2325
2326 Qualifiers ToQuals = ToPointee.getQualifiers();
2327 if (!ToPointee->isObjCLifetimeType() ||
2328 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002329 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002330 return false;
2331
2332 // Argument must be a pointer to __strong to __weak.
2333 QualType FromPointee;
2334 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2335 FromPointee = FromPointer->getPointeeType();
2336 else
2337 return false;
2338
2339 Qualifiers FromQuals = FromPointee.getQualifiers();
2340 if (!FromPointee->isObjCLifetimeType() ||
2341 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2342 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2343 return false;
2344
2345 // Make sure that we have compatible qualifiers.
2346 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2347 if (!ToQuals.compatiblyIncludes(FromQuals))
2348 return false;
2349
2350 // Remove qualifiers from the pointee type we're converting from; they
2351 // aren't used in the compatibility check belong, and we'll be adding back
2352 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2353 FromPointee = FromPointee.getUnqualifiedType();
2354
2355 // The unqualified form of the pointee types must be compatible.
2356 ToPointee = ToPointee.getUnqualifiedType();
2357 bool IncompatibleObjC;
2358 if (Context.typesAreCompatible(FromPointee, ToPointee))
2359 FromPointee = ToPointee;
2360 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2361 IncompatibleObjC))
2362 return false;
2363
2364 /// \brief Construct the type we're converting to, which is a pointer to
2365 /// __autoreleasing pointee.
2366 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2367 ConvertedType = Context.getPointerType(FromPointee);
2368 return true;
2369}
2370
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002371bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2372 QualType& ConvertedType) {
2373 QualType ToPointeeType;
2374 if (const BlockPointerType *ToBlockPtr =
2375 ToType->getAs<BlockPointerType>())
2376 ToPointeeType = ToBlockPtr->getPointeeType();
2377 else
2378 return false;
2379
2380 QualType FromPointeeType;
2381 if (const BlockPointerType *FromBlockPtr =
2382 FromType->getAs<BlockPointerType>())
2383 FromPointeeType = FromBlockPtr->getPointeeType();
2384 else
2385 return false;
2386 // We have pointer to blocks, check whether the only
2387 // differences in the argument and result types are in Objective-C
2388 // pointer conversions. If so, we permit the conversion.
2389
2390 const FunctionProtoType *FromFunctionType
2391 = FromPointeeType->getAs<FunctionProtoType>();
2392 const FunctionProtoType *ToFunctionType
2393 = ToPointeeType->getAs<FunctionProtoType>();
2394
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002395 if (!FromFunctionType || !ToFunctionType)
2396 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002397
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002398 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002399 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002400
2401 // Perform the quick checks that will tell us whether these
2402 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002403 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002404 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2405 return false;
2406
2407 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2408 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2409 if (FromEInfo != ToEInfo)
2410 return false;
2411
2412 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002413 if (Context.hasSameType(FromFunctionType->getReturnType(),
2414 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002415 // Okay, the types match exactly. Nothing to do.
2416 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002417 QualType RHS = FromFunctionType->getReturnType();
2418 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002419 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002420 !RHS.hasQualifiers() && LHS.hasQualifiers())
2421 LHS = LHS.getUnqualifiedType();
2422
2423 if (Context.hasSameType(RHS,LHS)) {
2424 // OK exact match.
2425 } else if (isObjCPointerConversion(RHS, LHS,
2426 ConvertedType, IncompatibleObjC)) {
2427 if (IncompatibleObjC)
2428 return false;
2429 // Okay, we have an Objective-C pointer conversion.
2430 }
2431 else
2432 return false;
2433 }
2434
2435 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002436 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002437 ArgIdx != NumArgs; ++ArgIdx) {
2438 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002439 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2440 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002441 if (Context.hasSameType(FromArgType, ToArgType)) {
2442 // Okay, the types match exactly. Nothing to do.
2443 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2444 ConvertedType, IncompatibleObjC)) {
2445 if (IncompatibleObjC)
2446 return false;
2447 // Okay, we have an Objective-C pointer conversion.
2448 } else
2449 // Argument types are too different. Abort.
2450 return false;
2451 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002452 if (LangOpts.ObjCAutoRefCount &&
2453 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2454 ToFunctionType))
2455 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002456
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002457 ConvertedType = ToType;
2458 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002459}
2460
Richard Trieucaff2472011-11-23 22:32:32 +00002461enum {
2462 ft_default,
2463 ft_different_class,
2464 ft_parameter_arity,
2465 ft_parameter_mismatch,
2466 ft_return_type,
2467 ft_qualifer_mismatch
2468};
2469
2470/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2471/// function types. Catches different number of parameter, mismatch in
2472/// parameter types, and different return types.
2473void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2474 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002475 // If either type is not valid, include no extra info.
2476 if (FromType.isNull() || ToType.isNull()) {
2477 PDiag << ft_default;
2478 return;
2479 }
2480
Richard Trieucaff2472011-11-23 22:32:32 +00002481 // Get the function type from the pointers.
2482 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2483 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2484 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002485 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002486 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2487 << QualType(FromMember->getClass(), 0);
2488 return;
2489 }
2490 FromType = FromMember->getPointeeType();
2491 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002492 }
2493
Richard Trieu96ed5b62011-12-13 23:19:45 +00002494 if (FromType->isPointerType())
2495 FromType = FromType->getPointeeType();
2496 if (ToType->isPointerType())
2497 ToType = ToType->getPointeeType();
2498
2499 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002500 FromType = FromType.getNonReferenceType();
2501 ToType = ToType.getNonReferenceType();
2502
Richard Trieucaff2472011-11-23 22:32:32 +00002503 // Don't print extra info for non-specialized template functions.
2504 if (FromType->isInstantiationDependentType() &&
2505 !FromType->getAs<TemplateSpecializationType>()) {
2506 PDiag << ft_default;
2507 return;
2508 }
2509
Richard Trieu96ed5b62011-12-13 23:19:45 +00002510 // No extra info for same types.
2511 if (Context.hasSameType(FromType, ToType)) {
2512 PDiag << ft_default;
2513 return;
2514 }
2515
Richard Trieucaff2472011-11-23 22:32:32 +00002516 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2517 *ToFunction = ToType->getAs<FunctionProtoType>();
2518
2519 // Both types need to be function types.
2520 if (!FromFunction || !ToFunction) {
2521 PDiag << ft_default;
2522 return;
2523 }
2524
Alp Toker9cacbab2014-01-20 20:26:09 +00002525 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2526 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2527 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002528 return;
2529 }
2530
2531 // Handle different parameter types.
2532 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002533 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002534 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002535 << ToFunction->getParamType(ArgPos)
2536 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002537 return;
2538 }
2539
2540 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002541 if (!Context.hasSameType(FromFunction->getReturnType(),
2542 ToFunction->getReturnType())) {
2543 PDiag << ft_return_type << ToFunction->getReturnType()
2544 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002545 return;
2546 }
2547
2548 unsigned FromQuals = FromFunction->getTypeQuals(),
2549 ToQuals = ToFunction->getTypeQuals();
2550 if (FromQuals != ToQuals) {
2551 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2552 return;
2553 }
2554
2555 // Unable to find a difference, so add no extra info.
2556 PDiag << ft_default;
2557}
2558
Alp Toker9cacbab2014-01-20 20:26:09 +00002559/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002560/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002561/// they have same number of arguments. If the parameters are different,
2562/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002563bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2564 const FunctionProtoType *NewType,
2565 unsigned *ArgPos) {
2566 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2567 N = NewType->param_type_begin(),
2568 E = OldType->param_type_end();
2569 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002570 if (!Context.hasSameType(O->getUnqualifiedType(),
2571 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002572 if (ArgPos)
2573 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002574 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002575 }
2576 }
2577 return true;
2578}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002579
Douglas Gregor39c16d42008-10-24 04:54:22 +00002580/// CheckPointerConversion - Check the pointer conversion from the
2581/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002582/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002583/// conversions for which IsPointerConversion has already returned
2584/// true. It returns true and produces a diagnostic if there was an
2585/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002586bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002587 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002588 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002589 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002590 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002591 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002592
John McCall8cb679e2010-11-15 09:13:47 +00002593 Kind = CK_BitCast;
2594
David Blaikie1c7c8f72012-08-08 17:33:31 +00002595 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002596 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002597 Expr::NPCK_ZeroExpression) {
2598 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2599 DiagRuntimeBehavior(From->getExprLoc(), From,
2600 PDiag(diag::warn_impcast_bool_to_null_pointer)
2601 << ToType << From->getSourceRange());
2602 else if (!isUnevaluatedContext())
2603 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2604 << ToType << From->getSourceRange();
2605 }
John McCall9320b872011-09-09 05:25:32 +00002606 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2607 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002608 QualType FromPointeeType = FromPtrType->getPointeeType(),
2609 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002610
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002611 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2612 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002613 // We must have a derived-to-base conversion. Check an
2614 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002615 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2616 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002617 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002618 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002619 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002620
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002621 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002622 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002623 }
2624 }
John McCall9320b872011-09-09 05:25:32 +00002625 } else if (const ObjCObjectPointerType *ToPtrType =
2626 ToType->getAs<ObjCObjectPointerType>()) {
2627 if (const ObjCObjectPointerType *FromPtrType =
2628 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002629 // Objective-C++ conversions are always okay.
2630 // FIXME: We should have a different class of conversions for the
2631 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002632 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002633 return false;
John McCall9320b872011-09-09 05:25:32 +00002634 } else if (FromType->isBlockPointerType()) {
2635 Kind = CK_BlockPointerToObjCPointerCast;
2636 } else {
2637 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002638 }
John McCall9320b872011-09-09 05:25:32 +00002639 } else if (ToType->isBlockPointerType()) {
2640 if (!FromType->isBlockPointerType())
2641 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002642 }
John McCall8cb679e2010-11-15 09:13:47 +00002643
2644 // We shouldn't fall into this case unless it's valid for other
2645 // reasons.
2646 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2647 Kind = CK_NullToPointer;
2648
Douglas Gregor39c16d42008-10-24 04:54:22 +00002649 return false;
2650}
2651
Sebastian Redl72b597d2009-01-25 19:43:20 +00002652/// IsMemberPointerConversion - Determines whether the conversion of the
2653/// expression From, which has the (possibly adjusted) type FromType, can be
2654/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2655/// If so, returns true and places the converted type (that might differ from
2656/// ToType in its cv-qualifiers at some level) into ConvertedType.
2657bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002658 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002659 bool InOverloadResolution,
2660 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002661 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002662 if (!ToTypePtr)
2663 return false;
2664
2665 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002666 if (From->isNullPointerConstant(Context,
2667 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2668 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002669 ConvertedType = ToType;
2670 return true;
2671 }
2672
2673 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002674 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002675 if (!FromTypePtr)
2676 return false;
2677
2678 // A pointer to member of B can be converted to a pointer to member of D,
2679 // where D is derived from B (C++ 4.11p2).
2680 QualType FromClass(FromTypePtr->getClass(), 0);
2681 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002682
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002683 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002684 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002685 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002686 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2687 ToClass.getTypePtr());
2688 return true;
2689 }
2690
2691 return false;
2692}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002693
Sebastian Redl72b597d2009-01-25 19:43:20 +00002694/// CheckMemberPointerConversion - Check the member pointer conversion from the
2695/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002696/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002697/// for which IsMemberPointerConversion has already returned true. It returns
2698/// true and produces a diagnostic if there was an error, or returns false
2699/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002700bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002701 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002702 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002703 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002704 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002705 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002706 if (!FromPtrType) {
2707 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002708 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002709 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002710 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002711 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002712 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002713 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002714
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002715 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002716 assert(ToPtrType && "No member pointer cast has a target type "
2717 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002718
Sebastian Redled8f2002009-01-28 18:33:18 +00002719 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2720 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002721
Sebastian Redled8f2002009-01-28 18:33:18 +00002722 // FIXME: What about dependent types?
2723 assert(FromClass->isRecordType() && "Pointer into non-class.");
2724 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002725
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002726 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002727 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002728 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2729 assert(DerivationOkay &&
2730 "Should not have been called if derivation isn't OK.");
2731 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002732
Sebastian Redled8f2002009-01-28 18:33:18 +00002733 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2734 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002735 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2736 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2737 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2738 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002739 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002740
Douglas Gregor89ee6822009-02-28 01:32:25 +00002741 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002742 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2743 << FromClass << ToClass << QualType(VBase, 0)
2744 << From->getSourceRange();
2745 return true;
2746 }
2747
John McCall5b0829a2010-02-10 09:31:12 +00002748 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002749 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2750 Paths.front(),
2751 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002752
Anders Carlssond7923c62009-08-22 23:33:40 +00002753 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002754 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002755 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002756 return false;
2757}
2758
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002759/// Determine whether the lifetime conversion between the two given
2760/// qualifiers sets is nontrivial.
2761static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2762 Qualifiers ToQuals) {
2763 // Converting anything to const __unsafe_unretained is trivial.
2764 if (ToQuals.hasConst() &&
2765 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2766 return false;
2767
2768 return true;
2769}
2770
Douglas Gregor9a657932008-10-21 23:43:52 +00002771/// IsQualificationConversion - Determines whether the conversion from
2772/// an rvalue of type FromType to ToType is a qualification conversion
2773/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002774///
2775/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2776/// when the qualification conversion involves a change in the Objective-C
2777/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002778bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002779Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002780 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002781 FromType = Context.getCanonicalType(FromType);
2782 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002783 ObjCLifetimeConversion = false;
2784
Douglas Gregor9a657932008-10-21 23:43:52 +00002785 // If FromType and ToType are the same type, this is not a
2786 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002787 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002788 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002789
Douglas Gregor9a657932008-10-21 23:43:52 +00002790 // (C++ 4.4p4):
2791 // A conversion can add cv-qualifiers at levels other than the first
2792 // in multi-level pointers, subject to the following rules: [...]
2793 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002794 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002795 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002796 // Within each iteration of the loop, we check the qualifiers to
2797 // determine if this still looks like a qualification
2798 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002799 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002800 // until there are no more pointers or pointers-to-members left to
2801 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002802 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002803
Douglas Gregor90609aa2011-04-25 18:40:17 +00002804 Qualifiers FromQuals = FromType.getQualifiers();
2805 Qualifiers ToQuals = ToType.getQualifiers();
2806
John McCall31168b02011-06-15 23:02:42 +00002807 // Objective-C ARC:
2808 // Check Objective-C lifetime conversions.
2809 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2810 UnwrappedAnyPointer) {
2811 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002812 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2813 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002814 FromQuals.removeObjCLifetime();
2815 ToQuals.removeObjCLifetime();
2816 } else {
2817 // Qualification conversions cannot cast between different
2818 // Objective-C lifetime qualifiers.
2819 return false;
2820 }
2821 }
2822
Douglas Gregorf30053d2011-05-08 06:09:53 +00002823 // Allow addition/removal of GC attributes but not changing GC attributes.
2824 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2825 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2826 FromQuals.removeObjCGCAttr();
2827 ToQuals.removeObjCGCAttr();
2828 }
2829
Douglas Gregor9a657932008-10-21 23:43:52 +00002830 // -- for every j > 0, if const is in cv 1,j then const is in cv
2831 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002832 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002833 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002834
Douglas Gregor9a657932008-10-21 23:43:52 +00002835 // -- if the cv 1,j and cv 2,j are different, then const is in
2836 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002837 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002838 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002839 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002840
Douglas Gregor9a657932008-10-21 23:43:52 +00002841 // Keep track of whether all prior cv-qualifiers in the "to" type
2842 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002843 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002844 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002845 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002846
2847 // We are left with FromType and ToType being the pointee types
2848 // after unwrapping the original FromType and ToType the same number
2849 // of types. If we unwrapped any pointers, and if FromType and
2850 // ToType have the same unqualified type (since we checked
2851 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002852 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002853}
2854
Douglas Gregorc79862f2012-04-12 17:51:55 +00002855/// \brief - Determine whether this is a conversion from a scalar type to an
2856/// atomic type.
2857///
2858/// If successful, updates \c SCS's second and third steps in the conversion
2859/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002860static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2861 bool InOverloadResolution,
2862 StandardConversionSequence &SCS,
2863 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002864 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2865 if (!ToAtomic)
2866 return false;
2867
2868 StandardConversionSequence InnerSCS;
2869 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2870 InOverloadResolution, InnerSCS,
2871 CStyle, /*AllowObjCWritebackConversion=*/false))
2872 return false;
2873
2874 SCS.Second = InnerSCS.Second;
2875 SCS.setToType(1, InnerSCS.getToType(1));
2876 SCS.Third = InnerSCS.Third;
2877 SCS.QualificationIncludesObjCLifetime
2878 = InnerSCS.QualificationIncludesObjCLifetime;
2879 SCS.setToType(2, InnerSCS.getToType(2));
2880 return true;
2881}
2882
Sebastian Redle5417162012-03-27 18:33:03 +00002883static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2884 CXXConstructorDecl *Constructor,
2885 QualType Type) {
2886 const FunctionProtoType *CtorType =
2887 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002888 if (CtorType->getNumParams() > 0) {
2889 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002890 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2891 return true;
2892 }
2893 return false;
2894}
2895
Sebastian Redl82ace982012-02-11 23:51:08 +00002896static OverloadingResult
2897IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2898 CXXRecordDecl *To,
2899 UserDefinedConversionSequence &User,
2900 OverloadCandidateSet &CandidateSet,
2901 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002902 DeclContext::lookup_result R = S.LookupConstructors(To);
2903 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002904 Con != ConEnd; ++Con) {
2905 NamedDecl *D = *Con;
2906 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2907
2908 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00002909 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002910 FunctionTemplateDecl *ConstructorTmpl
2911 = dyn_cast<FunctionTemplateDecl>(D);
2912 if (ConstructorTmpl)
2913 Constructor
2914 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2915 else
2916 Constructor = cast<CXXConstructorDecl>(D);
2917
2918 bool Usable = !Constructor->isInvalidDecl() &&
2919 S.isInitListConstructor(Constructor) &&
2920 (AllowExplicit || !Constructor->isExplicit());
2921 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002922 // If the first argument is (a reference to) the target type,
2923 // suppress conversions.
2924 bool SuppressUserConversions =
2925 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002926 if (ConstructorTmpl)
2927 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00002928 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002929 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002930 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002931 else
2932 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002933 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002934 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002935 }
2936 }
2937
2938 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2939
2940 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00002941 switch (auto Result =
2942 CandidateSet.BestViableFunction(S, From->getLocStart(),
2943 Best, true)) {
2944 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00002945 case OR_Success: {
2946 // Record the standard conversion we used and the conversion function.
2947 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002948 QualType ThisType = Constructor->getThisType(S.Context);
2949 // Initializer lists don't have conversions as such.
2950 User.Before.setAsIdentityConversion();
2951 User.HadMultipleCandidates = HadMultipleCandidates;
2952 User.ConversionFunction = Constructor;
2953 User.FoundConversionFunction = Best->FoundDecl;
2954 User.After.setAsIdentityConversion();
2955 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2956 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00002957 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00002958 }
2959
2960 case OR_No_Viable_Function:
2961 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00002962 case OR_Ambiguous:
2963 return OR_Ambiguous;
2964 }
2965
2966 llvm_unreachable("Invalid OverloadResult!");
2967}
2968
Douglas Gregor576e98c2009-01-30 23:27:23 +00002969/// Determines whether there is a user-defined conversion sequence
2970/// (C++ [over.ics.user]) that converts expression From to the type
2971/// ToType. If such a conversion exists, User will contain the
2972/// user-defined conversion sequence that performs such a conversion
2973/// and this routine will return true. Otherwise, this routine returns
2974/// false and User is unspecified.
2975///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002976/// \param AllowExplicit true if the conversion should consider C++0x
2977/// "explicit" conversion functions as well as non-explicit conversion
2978/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00002979///
2980/// \param AllowObjCConversionOnExplicit true if the conversion should
2981/// allow an extra Objective-C pointer conversion on uses of explicit
2982/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00002983static OverloadingResult
2984IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002985 UserDefinedConversionSequence &User,
2986 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00002987 bool AllowExplicit,
2988 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00002989 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00002990
Douglas Gregor5ab11652010-04-17 22:01:05 +00002991 // Whether we will only visit constructors.
2992 bool ConstructorsOnly = false;
2993
2994 // If the type we are conversion to is a class type, enumerate its
2995 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002996 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002997 // C++ [over.match.ctor]p1:
2998 // When objects of class type are direct-initialized (8.5), or
2999 // copy-initialized from an expression of the same or a
3000 // derived class type (8.5), overload resolution selects the
3001 // constructor. [...] For copy-initialization, the candidate
3002 // functions are all the converting constructors (12.3.1) of
3003 // that class. The argument list is the expression-list within
3004 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003005 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003006 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003007 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003008 ConstructorsOnly = true;
3009
Benjamin Kramer90633e32012-11-23 17:04:52 +00003010 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003011 // RequireCompleteType may have returned true due to some invalid decl
3012 // during template instantiation, but ToType may be complete enough now
3013 // to try to recover.
3014 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003015 // We're not going to find any constructors.
3016 } else if (CXXRecordDecl *ToRecordDecl
3017 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003018
3019 Expr **Args = &From;
3020 unsigned NumArgs = 1;
3021 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003022 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003023 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003024 OverloadingResult Result = IsInitializerListConstructorConversion(
3025 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3026 if (Result != OR_No_Viable_Function)
3027 return Result;
3028 // Never mind.
3029 CandidateSet.clear();
3030
3031 // If we're list-initializing, we pass the individual elements as
3032 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003033 Args = InitList->getInits();
3034 NumArgs = InitList->getNumInits();
3035 ListInitializing = true;
3036 }
3037
David Blaikieff7d47a2012-12-19 00:45:41 +00003038 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3039 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003040 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003041 NamedDecl *D = *Con;
3042 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3043
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003044 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003045 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003046 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003047 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003048 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003049 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003050 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3051 else
John McCalla0296f72010-03-19 07:35:19 +00003052 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003053
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003054 bool Usable = !Constructor->isInvalidDecl();
3055 if (ListInitializing)
3056 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3057 else
3058 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3059 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003060 bool SuppressUserConversions = !ConstructorsOnly;
3061 if (SuppressUserConversions && ListInitializing) {
3062 SuppressUserConversions = false;
3063 if (NumArgs == 1) {
3064 // If the first argument is (a reference to) the target type,
3065 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003066 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3067 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003068 }
3069 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003070 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003071 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003072 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003073 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003074 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003075 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003076 // Allow one user-defined conversion when user specifies a
3077 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003078 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003079 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003080 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003081 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003082 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003083 }
3084 }
3085
Douglas Gregor5ab11652010-04-17 22:01:05 +00003086 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003087 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003088 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003089 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003090 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003091 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003092 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003093 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3094 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003095 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3096 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003097 DeclAccessPair FoundDecl = I.getPair();
3098 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003099 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3100 if (isa<UsingShadowDecl>(D))
3101 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3102
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003103 CXXConversionDecl *Conv;
3104 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003105 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3106 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003107 else
John McCallda4458e2010-03-31 01:36:47 +00003108 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003109
3110 if (AllowExplicit || !Conv->isExplicit()) {
3111 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003112 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3113 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003114 CandidateSet,
3115 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003116 else
John McCall5c32be02010-08-24 20:38:10 +00003117 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003118 From, ToType, CandidateSet,
3119 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003120 }
3121 }
3122 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003123 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003124
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003125 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3126
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003127 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003128 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3129 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003130 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003131 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003132 // Record the standard conversion we used and the conversion function.
3133 if (CXXConstructorDecl *Constructor
3134 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3135 // C++ [over.ics.user]p1:
3136 // If the user-defined conversion is specified by a
3137 // constructor (12.3.1), the initial standard conversion
3138 // sequence converts the source type to the type required by
3139 // the argument of the constructor.
3140 //
3141 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003142 if (isa<InitListExpr>(From)) {
3143 // Initializer lists don't have conversions as such.
3144 User.Before.setAsIdentityConversion();
3145 } else {
3146 if (Best->Conversions[0].isEllipsis())
3147 User.EllipsisConversion = true;
3148 else {
3149 User.Before = Best->Conversions[0].Standard;
3150 User.EllipsisConversion = false;
3151 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003152 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003153 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003154 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003155 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003156 User.After.setAsIdentityConversion();
3157 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3158 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003159 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003160 }
3161 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003162 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3163 // C++ [over.ics.user]p1:
3164 //
3165 // [...] If the user-defined conversion is specified by a
3166 // conversion function (12.3.2), the initial standard
3167 // conversion sequence converts the source type to the
3168 // implicit object parameter of the conversion function.
3169 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003170 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003171 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003172 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003173 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003174
John McCall5c32be02010-08-24 20:38:10 +00003175 // C++ [over.ics.user]p2:
3176 // The second standard conversion sequence converts the
3177 // result of the user-defined conversion to the target type
3178 // for the sequence. Since an implicit conversion sequence
3179 // is an initialization, the special rules for
3180 // initialization by user-defined conversion apply when
3181 // selecting the best user-defined conversion for a
3182 // user-defined conversion sequence (see 13.3.3 and
3183 // 13.3.3.1).
3184 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003185 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003186 }
David Blaikie8a40f702012-01-17 06:56:22 +00003187 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003188
John McCall5c32be02010-08-24 20:38:10 +00003189 case OR_No_Viable_Function:
3190 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003191
John McCall5c32be02010-08-24 20:38:10 +00003192 case OR_Ambiguous:
3193 return OR_Ambiguous;
3194 }
3195
David Blaikie8a40f702012-01-17 06:56:22 +00003196 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003197}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003198
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003199bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003200Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003201 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003202 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3203 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003204 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003205 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003206 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003207 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003208 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3209 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003210 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003211 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003212 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003213 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003214 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3215 << From->getType() << From->getSourceRange() << ToType;
3216 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003217 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003218 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003219 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003220}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003221
Douglas Gregor2837aa22012-02-22 17:32:19 +00003222/// \brief Compare the user-defined conversion functions or constructors
3223/// of two user-defined conversion sequences to determine whether any ordering
3224/// is possible.
3225static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003226compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003227 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003228 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003229 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003230
Douglas Gregor2837aa22012-02-22 17:32:19 +00003231 // Objective-C++:
3232 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003233 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003234 // respectively, always prefer the conversion to a function pointer,
3235 // because the function pointer is more lightweight and is more likely
3236 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003237 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003238 if (!Conv1)
3239 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003240
Douglas Gregor2837aa22012-02-22 17:32:19 +00003241 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3242 if (!Conv2)
3243 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003244
Douglas Gregor2837aa22012-02-22 17:32:19 +00003245 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3246 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3247 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3248 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003249 return Block1 ? ImplicitConversionSequence::Worse
3250 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003251 }
3252
3253 return ImplicitConversionSequence::Indistinguishable;
3254}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003255
3256static bool hasDeprecatedStringLiteralToCharPtrConversion(
3257 const ImplicitConversionSequence &ICS) {
3258 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3259 (ICS.isUserDefined() &&
3260 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3261}
3262
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003263/// CompareImplicitConversionSequences - Compare two implicit
3264/// conversion sequences to determine whether one is better than the
3265/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003266static ImplicitConversionSequence::CompareKind
3267CompareImplicitConversionSequences(Sema &S,
3268 const ImplicitConversionSequence& ICS1,
3269 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003270{
3271 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3272 // conversion sequences (as defined in 13.3.3.1)
3273 // -- a standard conversion sequence (13.3.3.1.1) is a better
3274 // conversion sequence than a user-defined conversion sequence or
3275 // an ellipsis conversion sequence, and
3276 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3277 // conversion sequence than an ellipsis conversion sequence
3278 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003279 //
John McCall0d1da222010-01-12 00:44:57 +00003280 // C++0x [over.best.ics]p10:
3281 // For the purpose of ranking implicit conversion sequences as
3282 // described in 13.3.3.2, the ambiguous conversion sequence is
3283 // treated as a user-defined sequence that is indistinguishable
3284 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003285
3286 // String literal to 'char *' conversion has been deprecated in C++03. It has
3287 // been removed from C++11. We still accept this conversion, if it happens at
3288 // the best viable function. Otherwise, this conversion is considered worse
3289 // than ellipsis conversion. Consider this as an extension; this is not in the
3290 // standard. For example:
3291 //
3292 // int &f(...); // #1
3293 // void f(char*); // #2
3294 // void g() { int &r = f("foo"); }
3295 //
3296 // In C++03, we pick #2 as the best viable function.
3297 // In C++11, we pick #1 as the best viable function, because ellipsis
3298 // conversion is better than string-literal to char* conversion (since there
3299 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3300 // convert arguments, #2 would be the best viable function in C++11.
3301 // If the best viable function has this conversion, a warning will be issued
3302 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3303
3304 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3305 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3306 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3307 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3308 ? ImplicitConversionSequence::Worse
3309 : ImplicitConversionSequence::Better;
3310
Douglas Gregor5ab11652010-04-17 22:01:05 +00003311 if (ICS1.getKindRank() < ICS2.getKindRank())
3312 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003313 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003314 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003315
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003316 // The following checks require both conversion sequences to be of
3317 // the same kind.
3318 if (ICS1.getKind() != ICS2.getKind())
3319 return ImplicitConversionSequence::Indistinguishable;
3320
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003321 ImplicitConversionSequence::CompareKind Result =
3322 ImplicitConversionSequence::Indistinguishable;
3323
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003324 // Two implicit conversion sequences of the same form are
3325 // indistinguishable conversion sequences unless one of the
3326 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003327
3328 // List-initialization sequence L1 is a better conversion sequence than
3329 // list-initialization sequence L2 if:
3330 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3331 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003332 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003333 // and N1 is smaller than N2.,
3334 // even if one of the other rules in this paragraph would otherwise apply.
3335 if (!ICS1.isBad()) {
3336 if (ICS1.isStdInitializerListElement() &&
3337 !ICS2.isStdInitializerListElement())
3338 return ImplicitConversionSequence::Better;
3339 if (!ICS1.isStdInitializerListElement() &&
3340 ICS2.isStdInitializerListElement())
3341 return ImplicitConversionSequence::Worse;
3342 }
3343
John McCall0d1da222010-01-12 00:44:57 +00003344 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003345 // Standard conversion sequence S1 is a better conversion sequence than
3346 // standard conversion sequence S2 if [...]
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003347 Result = CompareStandardConversionSequences(S,
3348 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003349 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003350 // User-defined conversion sequence U1 is a better conversion
3351 // sequence than another user-defined conversion sequence U2 if
3352 // they contain the same user-defined conversion function or
3353 // constructor and if the second standard conversion sequence of
3354 // U1 is better than the second standard conversion sequence of
3355 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003356 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003357 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003358 Result = CompareStandardConversionSequences(S,
3359 ICS1.UserDefined.After,
3360 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003361 else
3362 Result = compareConversionFunctions(S,
3363 ICS1.UserDefined.ConversionFunction,
3364 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003365 }
3366
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003367 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003368}
3369
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003370static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3371 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3372 Qualifiers Quals;
3373 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003374 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003375 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003376
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003377 return Context.hasSameUnqualifiedType(T1, T2);
3378}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003379
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003380// Per 13.3.3.2p3, compare the given standard conversion sequences to
3381// determine if one is a proper subset of the other.
3382static ImplicitConversionSequence::CompareKind
3383compareStandardConversionSubsets(ASTContext &Context,
3384 const StandardConversionSequence& SCS1,
3385 const StandardConversionSequence& SCS2) {
3386 ImplicitConversionSequence::CompareKind Result
3387 = ImplicitConversionSequence::Indistinguishable;
3388
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003389 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003390 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003391 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3392 return ImplicitConversionSequence::Better;
3393 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3394 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003395
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003396 if (SCS1.Second != SCS2.Second) {
3397 if (SCS1.Second == ICK_Identity)
3398 Result = ImplicitConversionSequence::Better;
3399 else if (SCS2.Second == ICK_Identity)
3400 Result = ImplicitConversionSequence::Worse;
3401 else
3402 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003403 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003404 return ImplicitConversionSequence::Indistinguishable;
3405
3406 if (SCS1.Third == SCS2.Third) {
3407 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3408 : ImplicitConversionSequence::Indistinguishable;
3409 }
3410
3411 if (SCS1.Third == ICK_Identity)
3412 return Result == ImplicitConversionSequence::Worse
3413 ? ImplicitConversionSequence::Indistinguishable
3414 : ImplicitConversionSequence::Better;
3415
3416 if (SCS2.Third == ICK_Identity)
3417 return Result == ImplicitConversionSequence::Better
3418 ? ImplicitConversionSequence::Indistinguishable
3419 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003421 return ImplicitConversionSequence::Indistinguishable;
3422}
3423
Douglas Gregore696ebb2011-01-26 14:52:12 +00003424/// \brief Determine whether one of the given reference bindings is better
3425/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003426static bool
3427isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3428 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003429 // C++0x [over.ics.rank]p3b4:
3430 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3431 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003432 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003433 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003434 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003435 // reference*.
3436 //
3437 // FIXME: Rvalue references. We're going rogue with the above edits,
3438 // because the semantics in the current C++0x working paper (N3225 at the
3439 // time of this writing) break the standard definition of std::forward
3440 // and std::reference_wrapper when dealing with references to functions.
3441 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003442 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3443 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3444 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003445
Douglas Gregore696ebb2011-01-26 14:52:12 +00003446 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3447 SCS2.IsLvalueReference) ||
3448 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003449 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003450}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003451
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003452/// CompareStandardConversionSequences - Compare two standard
3453/// conversion sequences to determine whether one is better than the
3454/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003455static ImplicitConversionSequence::CompareKind
3456CompareStandardConversionSequences(Sema &S,
3457 const StandardConversionSequence& SCS1,
3458 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003459{
3460 // Standard conversion sequence S1 is a better conversion sequence
3461 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3462
3463 // -- S1 is a proper subsequence of S2 (comparing the conversion
3464 // sequences in the canonical form defined by 13.3.3.1.1,
3465 // excluding any Lvalue Transformation; the identity conversion
3466 // sequence is considered to be a subsequence of any
3467 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003468 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003469 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003470 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003471
3472 // -- the rank of S1 is better than the rank of S2 (by the rules
3473 // defined below), or, if not that,
3474 ImplicitConversionRank Rank1 = SCS1.getRank();
3475 ImplicitConversionRank Rank2 = SCS2.getRank();
3476 if (Rank1 < Rank2)
3477 return ImplicitConversionSequence::Better;
3478 else if (Rank2 < Rank1)
3479 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003480
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003481 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3482 // are indistinguishable unless one of the following rules
3483 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003484
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003485 // A conversion that is not a conversion of a pointer, or
3486 // pointer to member, to bool is better than another conversion
3487 // that is such a conversion.
3488 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3489 return SCS2.isPointerConversionToBool()
3490 ? ImplicitConversionSequence::Better
3491 : ImplicitConversionSequence::Worse;
3492
Douglas Gregor5c407d92008-10-23 00:40:37 +00003493 // C++ [over.ics.rank]p4b2:
3494 //
3495 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003496 // conversion of B* to A* is better than conversion of B* to
3497 // void*, and conversion of A* to void* is better than conversion
3498 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003499 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003500 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003501 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003502 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003503 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3504 // Exactly one of the conversion sequences is a conversion to
3505 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003506 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3507 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003508 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3509 // Neither conversion sequence converts to a void pointer; compare
3510 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003511 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003512 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003513 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003514 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3515 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003516 // Both conversion sequences are conversions to void
3517 // pointers. Compare the source types to determine if there's an
3518 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003519 QualType FromType1 = SCS1.getFromType();
3520 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003521
3522 // Adjust the types we're converting from via the array-to-pointer
3523 // conversion, if we need to.
3524 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003525 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003526 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003527 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003528
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003529 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3530 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003531
John McCall5c32be02010-08-24 20:38:10 +00003532 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003533 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003534 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003535 return ImplicitConversionSequence::Worse;
3536
3537 // Objective-C++: If one interface is more specific than the
3538 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003539 const ObjCObjectPointerType* FromObjCPtr1
3540 = FromType1->getAs<ObjCObjectPointerType>();
3541 const ObjCObjectPointerType* FromObjCPtr2
3542 = FromType2->getAs<ObjCObjectPointerType>();
3543 if (FromObjCPtr1 && FromObjCPtr2) {
3544 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3545 FromObjCPtr2);
3546 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3547 FromObjCPtr1);
3548 if (AssignLeft != AssignRight) {
3549 return AssignLeft? ImplicitConversionSequence::Better
3550 : ImplicitConversionSequence::Worse;
3551 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003552 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003553 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003554
3555 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3556 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003557 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003558 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003559 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003560
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003561 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003562 // Check for a better reference binding based on the kind of bindings.
3563 if (isBetterReferenceBindingKind(SCS1, SCS2))
3564 return ImplicitConversionSequence::Better;
3565 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3566 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003567
Sebastian Redlb28b4072009-03-22 23:49:27 +00003568 // C++ [over.ics.rank]p3b4:
3569 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3570 // which the references refer are the same type except for
3571 // top-level cv-qualifiers, and the type to which the reference
3572 // initialized by S2 refers is more cv-qualified than the type
3573 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003574 QualType T1 = SCS1.getToType(2);
3575 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003576 T1 = S.Context.getCanonicalType(T1);
3577 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003578 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003579 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3580 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003581 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003582 // Objective-C++ ARC: If the references refer to objects with different
3583 // lifetimes, prefer bindings that don't change lifetime.
3584 if (SCS1.ObjCLifetimeConversionBinding !=
3585 SCS2.ObjCLifetimeConversionBinding) {
3586 return SCS1.ObjCLifetimeConversionBinding
3587 ? ImplicitConversionSequence::Worse
3588 : ImplicitConversionSequence::Better;
3589 }
3590
Chandler Carruth8e543b32010-12-12 08:17:55 +00003591 // If the type is an array type, promote the element qualifiers to the
3592 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003593 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003594 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003595 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003596 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003597 if (T2.isMoreQualifiedThan(T1))
3598 return ImplicitConversionSequence::Better;
3599 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003600 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003601 }
3602 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003603
Francois Pichet08d2fa02011-09-18 21:37:37 +00003604 // In Microsoft mode, prefer an integral conversion to a
3605 // floating-to-integral conversion if the integral conversion
3606 // is between types of the same size.
3607 // For example:
3608 // void f(float);
3609 // void f(int);
3610 // int main {
3611 // long a;
3612 // f(a);
3613 // }
3614 // Here, MSVC will call f(int) instead of generating a compile error
3615 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003616 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3617 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003618 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003619 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003620 return ImplicitConversionSequence::Better;
3621
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003622 return ImplicitConversionSequence::Indistinguishable;
3623}
3624
3625/// CompareQualificationConversions - Compares two standard conversion
3626/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003627/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003628static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003629CompareQualificationConversions(Sema &S,
3630 const StandardConversionSequence& SCS1,
3631 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003632 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003633 // -- S1 and S2 differ only in their qualification conversion and
3634 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3635 // cv-qualification signature of type T1 is a proper subset of
3636 // the cv-qualification signature of type T2, and S1 is not the
3637 // deprecated string literal array-to-pointer conversion (4.2).
3638 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3639 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3640 return ImplicitConversionSequence::Indistinguishable;
3641
3642 // FIXME: the example in the standard doesn't use a qualification
3643 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003644 QualType T1 = SCS1.getToType(2);
3645 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003646 T1 = S.Context.getCanonicalType(T1);
3647 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003648 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003649 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3650 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003651
3652 // If the types are the same, we won't learn anything by unwrapped
3653 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003654 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003655 return ImplicitConversionSequence::Indistinguishable;
3656
Chandler Carruth607f38e2009-12-29 07:16:59 +00003657 // If the type is an array type, promote the element qualifiers to the type
3658 // for comparison.
3659 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003660 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003661 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003662 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003663
Mike Stump11289f42009-09-09 15:08:12 +00003664 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003665 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003666
3667 // Objective-C++ ARC:
3668 // Prefer qualification conversions not involving a change in lifetime
3669 // to qualification conversions that do not change lifetime.
3670 if (SCS1.QualificationIncludesObjCLifetime !=
3671 SCS2.QualificationIncludesObjCLifetime) {
3672 Result = SCS1.QualificationIncludesObjCLifetime
3673 ? ImplicitConversionSequence::Worse
3674 : ImplicitConversionSequence::Better;
3675 }
3676
John McCall5c32be02010-08-24 20:38:10 +00003677 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003678 // Within each iteration of the loop, we check the qualifiers to
3679 // determine if this still looks like a qualification
3680 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003681 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003682 // until there are no more pointers or pointers-to-members left
3683 // to unwrap. This essentially mimics what
3684 // IsQualificationConversion does, but here we're checking for a
3685 // strict subset of qualifiers.
3686 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3687 // The qualifiers are the same, so this doesn't tell us anything
3688 // about how the sequences rank.
3689 ;
3690 else if (T2.isMoreQualifiedThan(T1)) {
3691 // T1 has fewer qualifiers, so it could be the better sequence.
3692 if (Result == ImplicitConversionSequence::Worse)
3693 // Neither has qualifiers that are a subset of the other's
3694 // qualifiers.
3695 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003696
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003697 Result = ImplicitConversionSequence::Better;
3698 } else if (T1.isMoreQualifiedThan(T2)) {
3699 // T2 has fewer qualifiers, so it could be the better sequence.
3700 if (Result == ImplicitConversionSequence::Better)
3701 // Neither has qualifiers that are a subset of the other's
3702 // qualifiers.
3703 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003704
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003705 Result = ImplicitConversionSequence::Worse;
3706 } else {
3707 // Qualifiers are disjoint.
3708 return ImplicitConversionSequence::Indistinguishable;
3709 }
3710
3711 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003712 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003713 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003714 }
3715
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003716 // Check that the winning standard conversion sequence isn't using
3717 // the deprecated string literal array to pointer conversion.
3718 switch (Result) {
3719 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003720 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003721 Result = ImplicitConversionSequence::Indistinguishable;
3722 break;
3723
3724 case ImplicitConversionSequence::Indistinguishable:
3725 break;
3726
3727 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003728 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003729 Result = ImplicitConversionSequence::Indistinguishable;
3730 break;
3731 }
3732
3733 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003734}
3735
Douglas Gregor5c407d92008-10-23 00:40:37 +00003736/// CompareDerivedToBaseConversions - Compares two standard conversion
3737/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003738/// various kinds of derived-to-base conversions (C++
3739/// [over.ics.rank]p4b3). As part of these checks, we also look at
3740/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003741static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003742CompareDerivedToBaseConversions(Sema &S,
3743 const StandardConversionSequence& SCS1,
3744 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003745 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003746 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003747 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003748 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003749
3750 // Adjust the types we're converting from via the array-to-pointer
3751 // conversion, if we need to.
3752 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003753 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003754 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003755 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003756
3757 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003758 FromType1 = S.Context.getCanonicalType(FromType1);
3759 ToType1 = S.Context.getCanonicalType(ToType1);
3760 FromType2 = S.Context.getCanonicalType(FromType2);
3761 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003762
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003763 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003764 //
3765 // If class B is derived directly or indirectly from class A and
3766 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003767 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003768 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003769 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003770 SCS2.Second == ICK_Pointer_Conversion &&
3771 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3772 FromType1->isPointerType() && FromType2->isPointerType() &&
3773 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003774 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003775 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003776 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003777 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003778 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003779 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003780 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003781 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003782
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003783 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003784 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003785 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003786 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003787 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003788 return ImplicitConversionSequence::Worse;
3789 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003790
3791 // -- conversion of B* to A* is better than conversion of C* to A*,
3792 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003793 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003794 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003795 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003796 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003797 }
3798 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3799 SCS2.Second == ICK_Pointer_Conversion) {
3800 const ObjCObjectPointerType *FromPtr1
3801 = FromType1->getAs<ObjCObjectPointerType>();
3802 const ObjCObjectPointerType *FromPtr2
3803 = FromType2->getAs<ObjCObjectPointerType>();
3804 const ObjCObjectPointerType *ToPtr1
3805 = ToType1->getAs<ObjCObjectPointerType>();
3806 const ObjCObjectPointerType *ToPtr2
3807 = ToType2->getAs<ObjCObjectPointerType>();
3808
3809 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3810 // Apply the same conversion ranking rules for Objective-C pointer types
3811 // that we do for C++ pointers to class types. However, we employ the
3812 // Objective-C pseudo-subtyping relationship used for assignment of
3813 // Objective-C pointer types.
3814 bool FromAssignLeft
3815 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3816 bool FromAssignRight
3817 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3818 bool ToAssignLeft
3819 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3820 bool ToAssignRight
3821 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3822
3823 // A conversion to an a non-id object pointer type or qualified 'id'
3824 // type is better than a conversion to 'id'.
3825 if (ToPtr1->isObjCIdType() &&
3826 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3827 return ImplicitConversionSequence::Worse;
3828 if (ToPtr2->isObjCIdType() &&
3829 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3830 return ImplicitConversionSequence::Better;
3831
3832 // A conversion to a non-id object pointer type is better than a
3833 // conversion to a qualified 'id' type
3834 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3835 return ImplicitConversionSequence::Worse;
3836 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3837 return ImplicitConversionSequence::Better;
3838
3839 // A conversion to an a non-Class object pointer type or qualified 'Class'
3840 // type is better than a conversion to 'Class'.
3841 if (ToPtr1->isObjCClassType() &&
3842 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3843 return ImplicitConversionSequence::Worse;
3844 if (ToPtr2->isObjCClassType() &&
3845 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3846 return ImplicitConversionSequence::Better;
3847
3848 // A conversion to a non-Class object pointer type is better than a
3849 // conversion to a qualified 'Class' type.
3850 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3851 return ImplicitConversionSequence::Worse;
3852 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3853 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003854
Douglas Gregor058d3de2011-01-31 18:51:41 +00003855 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3856 if (S.Context.hasSameType(FromType1, FromType2) &&
3857 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3858 (ToAssignLeft != ToAssignRight))
3859 return ToAssignLeft? ImplicitConversionSequence::Worse
3860 : ImplicitConversionSequence::Better;
3861
3862 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3863 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3864 (FromAssignLeft != FromAssignRight))
3865 return FromAssignLeft? ImplicitConversionSequence::Better
3866 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003867 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003868 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003869
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003870 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003871 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3872 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3873 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003874 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003875 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003876 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003877 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003878 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003879 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003880 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003881 ToType2->getAs<MemberPointerType>();
3882 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3883 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3884 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3885 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3886 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3887 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3888 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3889 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003890 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003891 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003892 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003893 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003894 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003895 return ImplicitConversionSequence::Better;
3896 }
3897 // conversion of B::* to C::* is better than conversion of A::* to C::*
3898 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003899 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003900 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003901 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003902 return ImplicitConversionSequence::Worse;
3903 }
3904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003905
Douglas Gregor5ab11652010-04-17 22:01:05 +00003906 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003907 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003908 // -- binding of an expression of type C to a reference of type
3909 // B& is better than binding an expression of type C to a
3910 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003911 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3912 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3913 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003914 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003915 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003916 return ImplicitConversionSequence::Worse;
3917 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003918
Douglas Gregor2fe98832008-11-03 19:09:14 +00003919 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003920 // -- binding of an expression of type B to a reference of type
3921 // A& is better than binding an expression of type C to a
3922 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003923 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3924 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3925 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003926 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003927 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003928 return ImplicitConversionSequence::Worse;
3929 }
3930 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003931
Douglas Gregor5c407d92008-10-23 00:40:37 +00003932 return ImplicitConversionSequence::Indistinguishable;
3933}
3934
Douglas Gregor45bb4832013-03-26 23:36:30 +00003935/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3936/// C++ class.
3937static bool isTypeValid(QualType T) {
3938 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3939 return !Record->isInvalidDecl();
3940
3941 return true;
3942}
3943
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003944/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3945/// determine whether they are reference-related,
3946/// reference-compatible, reference-compatible with added
3947/// qualification, or incompatible, for use in C++ initialization by
3948/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3949/// type, and the first type (T1) is the pointee type of the reference
3950/// type being initialized.
3951Sema::ReferenceCompareResult
3952Sema::CompareReferenceRelationship(SourceLocation Loc,
3953 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003954 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003955 bool &ObjCConversion,
3956 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003957 assert(!OrigT1->isReferenceType() &&
3958 "T1 must be the pointee type of the reference type");
3959 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3960
3961 QualType T1 = Context.getCanonicalType(OrigT1);
3962 QualType T2 = Context.getCanonicalType(OrigT2);
3963 Qualifiers T1Quals, T2Quals;
3964 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3965 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3966
3967 // C++ [dcl.init.ref]p4:
3968 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3969 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3970 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003971 DerivedToBase = false;
3972 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003973 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003974 if (UnqualT1 == UnqualT2) {
3975 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003976 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00003977 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3978 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003979 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003980 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3981 UnqualT2->isObjCObjectOrInterfaceType() &&
3982 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3983 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003984 else
3985 return Ref_Incompatible;
3986
3987 // At this point, we know that T1 and T2 are reference-related (at
3988 // least).
3989
3990 // If the type is an array type, promote the element qualifiers to the type
3991 // for comparison.
3992 if (isa<ArrayType>(T1) && T1Quals)
3993 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3994 if (isa<ArrayType>(T2) && T2Quals)
3995 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3996
3997 // C++ [dcl.init.ref]p4:
3998 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3999 // reference-related to T2 and cv1 is the same cv-qualification
4000 // as, or greater cv-qualification than, cv2. For purposes of
4001 // overload resolution, cases for which cv1 is greater
4002 // cv-qualification than cv2 are identified as
4003 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004004 //
4005 // Note that we also require equivalence of Objective-C GC and address-space
4006 // qualifiers when performing these computations, so that e.g., an int in
4007 // address space 1 is not reference-compatible with an int in address
4008 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004009 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4010 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004011 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4012 ObjCLifetimeConversion = true;
4013
John McCall31168b02011-06-15 23:02:42 +00004014 T1Quals.removeObjCLifetime();
4015 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004016 }
4017
Douglas Gregord517d552011-04-28 17:56:11 +00004018 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004019 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004020 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004021 return Ref_Compatible_With_Added_Qualification;
4022 else
4023 return Ref_Related;
4024}
4025
Douglas Gregor836a7e82010-08-11 02:15:33 +00004026/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004027/// with DeclType. Return true if something definite is found.
4028static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004029FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4030 QualType DeclType, SourceLocation DeclLoc,
4031 Expr *Init, QualType T2, bool AllowRvalues,
4032 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004033 assert(T2->isRecordType() && "Can only find conversions of record types.");
4034 CXXRecordDecl *T2RecordDecl
4035 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4036
Richard Smith100b24a2014-04-17 01:52:14 +00004037 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004038 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4039 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004040 NamedDecl *D = *I;
4041 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4042 if (isa<UsingShadowDecl>(D))
4043 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4044
4045 FunctionTemplateDecl *ConvTemplate
4046 = dyn_cast<FunctionTemplateDecl>(D);
4047 CXXConversionDecl *Conv;
4048 if (ConvTemplate)
4049 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4050 else
4051 Conv = cast<CXXConversionDecl>(D);
4052
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004053 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004054 // explicit conversions, skip it.
4055 if (!AllowExplicit && Conv->isExplicit())
4056 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057
Douglas Gregor836a7e82010-08-11 02:15:33 +00004058 if (AllowRvalues) {
4059 bool DerivedToBase = false;
4060 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004061 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004062
4063 // If we are initializing an rvalue reference, don't permit conversion
4064 // functions that return lvalues.
4065 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4066 const ReferenceType *RefType
4067 = Conv->getConversionType()->getAs<LValueReferenceType>();
4068 if (RefType && !RefType->getPointeeType()->isFunctionType())
4069 continue;
4070 }
4071
Douglas Gregor836a7e82010-08-11 02:15:33 +00004072 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004073 S.CompareReferenceRelationship(
4074 DeclLoc,
4075 Conv->getConversionType().getNonReferenceType()
4076 .getUnqualifiedType(),
4077 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004078 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004079 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004080 continue;
4081 } else {
4082 // If the conversion function doesn't return a reference type,
4083 // it can't be considered for this conversion. An rvalue reference
4084 // is only acceptable if its referencee is a function type.
4085
4086 const ReferenceType *RefType =
4087 Conv->getConversionType()->getAs<ReferenceType>();
4088 if (!RefType ||
4089 (!RefType->isLValueReferenceType() &&
4090 !RefType->getPointeeType()->isFunctionType()))
4091 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004093
Douglas Gregor836a7e82010-08-11 02:15:33 +00004094 if (ConvTemplate)
4095 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004096 Init, DeclType, CandidateSet,
4097 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004098 else
4099 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004100 DeclType, CandidateSet,
4101 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004102 }
4103
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004104 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4105
Sebastian Redld92badf2010-06-30 18:13:39 +00004106 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004107 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004108 case OR_Success:
4109 // C++ [over.ics.ref]p1:
4110 //
4111 // [...] If the parameter binds directly to the result of
4112 // applying a conversion function to the argument
4113 // expression, the implicit conversion sequence is a
4114 // user-defined conversion sequence (13.3.3.1.2), with the
4115 // second standard conversion sequence either an identity
4116 // conversion or, if the conversion function returns an
4117 // entity of a type that is a derived class of the parameter
4118 // type, a derived-to-base Conversion.
4119 if (!Best->FinalConversion.DirectBinding)
4120 return false;
4121
4122 ICS.setUserDefined();
4123 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4124 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004125 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004126 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004127 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004128 ICS.UserDefined.EllipsisConversion = false;
4129 assert(ICS.UserDefined.After.ReferenceBinding &&
4130 ICS.UserDefined.After.DirectBinding &&
4131 "Expected a direct reference binding!");
4132 return true;
4133
4134 case OR_Ambiguous:
4135 ICS.setAmbiguous();
4136 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4137 Cand != CandidateSet.end(); ++Cand)
4138 if (Cand->Viable)
4139 ICS.Ambiguous.addConversion(Cand->Function);
4140 return true;
4141
4142 case OR_No_Viable_Function:
4143 case OR_Deleted:
4144 // There was no suitable conversion, or we found a deleted
4145 // conversion; continue with other checks.
4146 return false;
4147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004148
David Blaikie8a40f702012-01-17 06:56:22 +00004149 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004150}
4151
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004152/// \brief Compute an implicit conversion sequence for reference
4153/// initialization.
4154static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004155TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004156 SourceLocation DeclLoc,
4157 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004158 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004159 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4160
4161 // Most paths end in a failed conversion.
4162 ImplicitConversionSequence ICS;
4163 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4164
4165 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4166 QualType T2 = Init->getType();
4167
4168 // If the initializer is the address of an overloaded function, try
4169 // to resolve the overloaded function. If all goes well, T2 is the
4170 // type of the resulting function.
4171 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4172 DeclAccessPair Found;
4173 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4174 false, Found))
4175 T2 = Fn->getType();
4176 }
4177
4178 // Compute some basic properties of the types and the initializer.
4179 bool isRValRef = DeclType->isRValueReferenceType();
4180 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004181 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004182 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004183 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004184 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004185 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004186 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004187
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004188
Sebastian Redld92badf2010-06-30 18:13:39 +00004189 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004190 // A reference to type "cv1 T1" is initialized by an expression
4191 // of type "cv2 T2" as follows:
4192
Sebastian Redld92badf2010-06-30 18:13:39 +00004193 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004194 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004195 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4196 // reference-compatible with "cv2 T2," or
4197 //
4198 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4199 if (InitCategory.isLValue() &&
4200 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004201 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004202 // When a parameter of reference type binds directly (8.5.3)
4203 // to an argument expression, the implicit conversion sequence
4204 // is the identity conversion, unless the argument expression
4205 // has a type that is a derived class of the parameter type,
4206 // in which case the implicit conversion sequence is a
4207 // derived-to-base Conversion (13.3.3.1).
4208 ICS.setStandard();
4209 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004210 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4211 : ObjCConversion? ICK_Compatible_Conversion
4212 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004213 ICS.Standard.Third = ICK_Identity;
4214 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4215 ICS.Standard.setToType(0, T2);
4216 ICS.Standard.setToType(1, T1);
4217 ICS.Standard.setToType(2, T1);
4218 ICS.Standard.ReferenceBinding = true;
4219 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004220 ICS.Standard.IsLvalueReference = !isRValRef;
4221 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4222 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004223 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004224 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004225 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004226 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004227
Sebastian Redld92badf2010-06-30 18:13:39 +00004228 // Nothing more to do: the inaccessibility/ambiguity check for
4229 // derived-to-base conversions is suppressed when we're
4230 // computing the implicit conversion sequence (C++
4231 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004232 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004233 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004234
Sebastian Redld92badf2010-06-30 18:13:39 +00004235 // -- has a class type (i.e., T2 is a class type), where T1 is
4236 // not reference-related to T2, and can be implicitly
4237 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4238 // is reference-compatible with "cv3 T3" 92) (this
4239 // conversion is selected by enumerating the applicable
4240 // conversion functions (13.3.1.6) and choosing the best
4241 // one through overload resolution (13.3)),
4242 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004243 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004244 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004245 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4246 Init, T2, /*AllowRvalues=*/false,
4247 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004248 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004249 }
4250 }
4251
Sebastian Redld92badf2010-06-30 18:13:39 +00004252 // -- Otherwise, the reference shall be an lvalue reference to a
4253 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004254 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004255 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004256 return ICS;
4257
Douglas Gregorf143cd52011-01-24 16:14:37 +00004258 // -- If the initializer expression
4259 //
4260 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004261 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004262 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4263 (InitCategory.isXValue() ||
4264 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4265 (InitCategory.isLValue() && T2->isFunctionType()))) {
4266 ICS.setStandard();
4267 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004269 : ObjCConversion? ICK_Compatible_Conversion
4270 : ICK_Identity;
4271 ICS.Standard.Third = ICK_Identity;
4272 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4273 ICS.Standard.setToType(0, T2);
4274 ICS.Standard.setToType(1, T1);
4275 ICS.Standard.setToType(2, T1);
4276 ICS.Standard.ReferenceBinding = true;
4277 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4278 // binding unless we're binding to a class prvalue.
4279 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4280 // allow the use of rvalue references in C++98/03 for the benefit of
4281 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004282 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004283 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004284 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004285 ICS.Standard.IsLvalueReference = !isRValRef;
4286 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004288 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004289 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004290 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004291 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294
Douglas Gregorf143cd52011-01-24 16:14:37 +00004295 // -- has a class type (i.e., T2 is a class type), where T1 is not
4296 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004297 // an xvalue, class prvalue, or function lvalue of type
4298 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004299 // "cv3 T3",
4300 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004302 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004303 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004304 // class subobject).
4305 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004307 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4308 Init, T2, /*AllowRvalues=*/true,
4309 AllowExplicit)) {
4310 // In the second case, if the reference is an rvalue reference
4311 // and the second standard conversion sequence of the
4312 // user-defined conversion sequence includes an lvalue-to-rvalue
4313 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004315 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4316 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4317
Douglas Gregor95273c32011-01-21 16:36:05 +00004318 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004319 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004320
Richard Smith19172c42014-07-14 02:28:44 +00004321 // A temporary of function type cannot be created; don't even try.
4322 if (T1->isFunctionType())
4323 return ICS;
4324
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004325 // -- Otherwise, a temporary of type "cv1 T1" is created and
4326 // initialized from the initializer expression using the
4327 // rules for a non-reference copy initialization (8.5). The
4328 // reference is then bound to the temporary. If T1 is
4329 // reference-related to T2, cv1 must be the same
4330 // cv-qualification as, or greater cv-qualification than,
4331 // cv2; otherwise, the program is ill-formed.
4332 if (RefRelationship == Sema::Ref_Related) {
4333 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4334 // we would be reference-compatible or reference-compatible with
4335 // added qualification. But that wasn't the case, so the reference
4336 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004337 //
4338 // Note that we only want to check address spaces and cvr-qualifiers here.
4339 // ObjC GC and lifetime qualifiers aren't important.
4340 Qualifiers T1Quals = T1.getQualifiers();
4341 Qualifiers T2Quals = T2.getQualifiers();
4342 T1Quals.removeObjCGCAttr();
4343 T1Quals.removeObjCLifetime();
4344 T2Quals.removeObjCGCAttr();
4345 T2Quals.removeObjCLifetime();
4346 if (!T1Quals.compatiblyIncludes(T2Quals))
4347 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004348 }
4349
4350 // If at least one of the types is a class type, the types are not
4351 // related, and we aren't allowed any user conversions, the
4352 // reference binding fails. This case is important for breaking
4353 // recursion, since TryImplicitConversion below will attempt to
4354 // create a temporary through the use of a copy constructor.
4355 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4356 (T1->isRecordType() || T2->isRecordType()))
4357 return ICS;
4358
Douglas Gregorcba72b12011-01-21 05:18:22 +00004359 // If T1 is reference-related to T2 and the reference is an rvalue
4360 // reference, the initializer expression shall not be an lvalue.
4361 if (RefRelationship >= Sema::Ref_Related &&
4362 isRValRef && Init->Classify(S.Context).isLValue())
4363 return ICS;
4364
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004365 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004366 // When a parameter of reference type is not bound directly to
4367 // an argument expression, the conversion sequence is the one
4368 // required to convert the argument expression to the
4369 // underlying type of the reference according to
4370 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4371 // to copy-initializing a temporary of the underlying type with
4372 // the argument expression. Any difference in top-level
4373 // cv-qualification is subsumed by the initialization itself
4374 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004375 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4376 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004377 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004378 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004379 /*AllowObjCWritebackConversion=*/false,
4380 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004381
4382 // Of course, that's still a reference binding.
4383 if (ICS.isStandard()) {
4384 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004385 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004386 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004387 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004388 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004389 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004390 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004391 const ReferenceType *LValRefType =
4392 ICS.UserDefined.ConversionFunction->getReturnType()
4393 ->getAs<LValueReferenceType>();
4394
4395 // C++ [over.ics.ref]p3:
4396 // Except for an implicit object parameter, for which see 13.3.1, a
4397 // standard conversion sequence cannot be formed if it requires [...]
4398 // binding an rvalue reference to an lvalue other than a function
4399 // lvalue.
4400 // Note that the function case is not possible here.
4401 if (DeclType->isRValueReferenceType() && LValRefType) {
4402 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4403 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4404 // reference to an rvalue!
4405 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4406 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004407 }
Richard Smith19172c42014-07-14 02:28:44 +00004408
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004409 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004410 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004411 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004412 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4413 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004414 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4415 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004416 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004417
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004418 return ICS;
4419}
4420
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004421static ImplicitConversionSequence
4422TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4423 bool SuppressUserConversions,
4424 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004425 bool AllowObjCWritebackConversion,
4426 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004427
4428/// TryListConversion - Try to copy-initialize a value of type ToType from the
4429/// initializer list From.
4430static ImplicitConversionSequence
4431TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4432 bool SuppressUserConversions,
4433 bool InOverloadResolution,
4434 bool AllowObjCWritebackConversion) {
4435 // C++11 [over.ics.list]p1:
4436 // When an argument is an initializer list, it is not an expression and
4437 // special rules apply for converting it to a parameter type.
4438
4439 ImplicitConversionSequence Result;
4440 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4441
Sebastian Redl09edce02012-01-23 22:09:39 +00004442 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004443 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004444 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004445 return Result;
4446
Larisse Voufo19d08672015-01-27 18:47:05 +00004447 // Per DR1467:
4448 // If the parameter type is a class X and the initializer list has a single
4449 // element of type cv U, where U is X or a class derived from X, the
4450 // implicit conversion sequence is the one required to convert the element
4451 // to the parameter type.
4452 //
4453 // Otherwise, if the parameter type is a character array [... ]
4454 // and the initializer list has a single element that is an
4455 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4456 // implicit conversion sequence is the identity conversion.
4457 if (From->getNumInits() == 1) {
4458 if (ToType->isRecordType()) {
4459 QualType InitType = From->getInit(0)->getType();
4460 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4461 S.IsDerivedFrom(InitType, ToType))
4462 return TryCopyInitialization(S, From->getInit(0), ToType,
4463 SuppressUserConversions,
4464 InOverloadResolution,
4465 AllowObjCWritebackConversion);
4466 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004467 // FIXME: Check the other conditions here: array of character type,
4468 // initializer is a string literal.
4469 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004470 InitializedEntity Entity =
4471 InitializedEntity::InitializeParameter(S.Context, ToType,
4472 /*Consumed=*/false);
4473 if (S.CanPerformCopyInitialization(Entity, From)) {
4474 Result.setStandard();
4475 Result.Standard.setAsIdentityConversion();
4476 Result.Standard.setFromType(ToType);
4477 Result.Standard.setAllToTypes(ToType);
4478 return Result;
4479 }
4480 }
4481 }
4482
4483 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004484 // C++11 [over.ics.list]p2:
4485 // If the parameter type is std::initializer_list<X> or "array of X" and
4486 // all the elements can be implicitly converted to X, the implicit
4487 // conversion sequence is the worst conversion necessary to convert an
4488 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004489 //
4490 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004491 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004492 // list has exactly N elements or if it has fewer than N elements and X is
4493 // default-constructible, and if all the elements of the initializer list
4494 // can be implicitly converted to X, the implicit conversion sequence is
4495 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004496 //
4497 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004498 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004499 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004500 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004501 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004502 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004503 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004504 if (!X.isNull()) {
4505 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4506 Expr *Init = From->getInit(i);
4507 ImplicitConversionSequence ICS =
4508 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4509 InOverloadResolution,
4510 AllowObjCWritebackConversion);
4511 // If a single element isn't convertible, fail.
4512 if (ICS.isBad()) {
4513 Result = ICS;
4514 break;
4515 }
4516 // Otherwise, look for the worst conversion.
4517 if (Result.isBad() ||
4518 CompareImplicitConversionSequences(S, ICS, Result) ==
4519 ImplicitConversionSequence::Worse)
4520 Result = ICS;
4521 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004522
4523 // For an empty list, we won't have computed any conversion sequence.
4524 // Introduce the identity conversion sequence.
4525 if (From->getNumInits() == 0) {
4526 Result.setStandard();
4527 Result.Standard.setAsIdentityConversion();
4528 Result.Standard.setFromType(ToType);
4529 Result.Standard.setAllToTypes(ToType);
4530 }
4531
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004532 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004533 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004534 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004535
Larisse Voufo19d08672015-01-27 18:47:05 +00004536 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004537 // C++11 [over.ics.list]p3:
4538 // Otherwise, if the parameter is a non-aggregate class X and overload
4539 // resolution chooses a single best constructor [...] the implicit
4540 // conversion sequence is a user-defined conversion sequence. If multiple
4541 // constructors are viable but none is better than the others, the
4542 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004543 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4544 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004545 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4546 /*AllowExplicit=*/false,
4547 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004548 AllowObjCWritebackConversion,
4549 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004550 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004551
Larisse Voufo19d08672015-01-27 18:47:05 +00004552 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004553 // C++11 [over.ics.list]p4:
4554 // Otherwise, if the parameter has an aggregate type which can be
4555 // initialized from the initializer list [...] the implicit conversion
4556 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004557 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004558 // Type is an aggregate, argument is an init list. At this point it comes
4559 // down to checking whether the initialization works.
4560 // FIXME: Find out whether this parameter is consumed or not.
4561 InitializedEntity Entity =
4562 InitializedEntity::InitializeParameter(S.Context, ToType,
4563 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004564 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004565 Result.setUserDefined();
4566 Result.UserDefined.Before.setAsIdentityConversion();
4567 // Initializer lists don't have a type.
4568 Result.UserDefined.Before.setFromType(QualType());
4569 Result.UserDefined.Before.setAllToTypes(QualType());
4570
4571 Result.UserDefined.After.setAsIdentityConversion();
4572 Result.UserDefined.After.setFromType(ToType);
4573 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004574 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004575 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004576 return Result;
4577 }
4578
Larisse Voufo19d08672015-01-27 18:47:05 +00004579 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004580 // C++11 [over.ics.list]p5:
4581 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004582 if (ToType->isReferenceType()) {
4583 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4584 // mention initializer lists in any way. So we go by what list-
4585 // initialization would do and try to extrapolate from that.
4586
4587 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4588
4589 // If the initializer list has a single element that is reference-related
4590 // to the parameter type, we initialize the reference from that.
4591 if (From->getNumInits() == 1) {
4592 Expr *Init = From->getInit(0);
4593
4594 QualType T2 = Init->getType();
4595
4596 // If the initializer is the address of an overloaded function, try
4597 // to resolve the overloaded function. If all goes well, T2 is the
4598 // type of the resulting function.
4599 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4600 DeclAccessPair Found;
4601 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4602 Init, ToType, false, Found))
4603 T2 = Fn->getType();
4604 }
4605
4606 // Compute some basic properties of the types and the initializer.
4607 bool dummy1 = false;
4608 bool dummy2 = false;
4609 bool dummy3 = false;
4610 Sema::ReferenceCompareResult RefRelationship
4611 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4612 dummy2, dummy3);
4613
Richard Smith4d2bbd72013-09-06 01:22:42 +00004614 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004615 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4616 SuppressUserConversions,
4617 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004618 }
Sebastian Redldf888642011-12-03 14:54:30 +00004619 }
4620
4621 // Otherwise, we bind the reference to a temporary created from the
4622 // initializer list.
4623 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4624 InOverloadResolution,
4625 AllowObjCWritebackConversion);
4626 if (Result.isFailure())
4627 return Result;
4628 assert(!Result.isEllipsis() &&
4629 "Sub-initialization cannot result in ellipsis conversion.");
4630
4631 // Can we even bind to a temporary?
4632 if (ToType->isRValueReferenceType() ||
4633 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4634 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4635 Result.UserDefined.After;
4636 SCS.ReferenceBinding = true;
4637 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4638 SCS.BindsToRvalue = true;
4639 SCS.BindsToFunctionLvalue = false;
4640 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4641 SCS.ObjCLifetimeConversionBinding = false;
4642 } else
4643 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4644 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004645 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004646 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004647
Larisse Voufo19d08672015-01-27 18:47:05 +00004648 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004649 // C++11 [over.ics.list]p6:
4650 // Otherwise, if the parameter type is not a class:
4651 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004652 // - if the initializer list has one element that is not itself an
4653 // initializer list, the implicit conversion sequence is the one
4654 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004655 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004656 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004657 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4658 SuppressUserConversions,
4659 InOverloadResolution,
4660 AllowObjCWritebackConversion);
4661 // - if the initializer list has no elements, the implicit conversion
4662 // sequence is the identity conversion.
4663 else if (NumInits == 0) {
4664 Result.setStandard();
4665 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004666 Result.Standard.setFromType(ToType);
4667 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004668 }
4669 return Result;
4670 }
4671
Larisse Voufo19d08672015-01-27 18:47:05 +00004672 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004673 // C++11 [over.ics.list]p7:
4674 // In all cases other than those enumerated above, no conversion is possible
4675 return Result;
4676}
4677
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004678/// TryCopyInitialization - Try to copy-initialize a value of type
4679/// ToType from the expression From. Return the implicit conversion
4680/// sequence required to pass this argument, which may be a bad
4681/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004682/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004683/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004684static ImplicitConversionSequence
4685TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004686 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004687 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004688 bool AllowObjCWritebackConversion,
4689 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004690 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4691 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4692 InOverloadResolution,AllowObjCWritebackConversion);
4693
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004694 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004695 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004696 /*FIXME:*/From->getLocStart(),
4697 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004698 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004699
John McCall5c32be02010-08-24 20:38:10 +00004700 return TryImplicitConversion(S, From, ToType,
4701 SuppressUserConversions,
4702 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004703 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004704 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004705 AllowObjCWritebackConversion,
4706 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004707}
4708
Anna Zaks1b068122011-07-28 19:46:48 +00004709static bool TryCopyInitialization(const CanQualType FromQTy,
4710 const CanQualType ToQTy,
4711 Sema &S,
4712 SourceLocation Loc,
4713 ExprValueKind FromVK) {
4714 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4715 ImplicitConversionSequence ICS =
4716 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4717
4718 return !ICS.isBad();
4719}
4720
Douglas Gregor436424c2008-11-18 23:14:02 +00004721/// TryObjectArgumentInitialization - Try to initialize the object
4722/// parameter of the given member function (@c Method) from the
4723/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004724static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004725TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004726 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004727 CXXMethodDecl *Method,
4728 CXXRecordDecl *ActingContext) {
4729 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004730 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4731 // const volatile object.
4732 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4733 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004734 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004735
4736 // Set up the conversion sequence as a "bad" conversion, to allow us
4737 // to exit early.
4738 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004739
4740 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004741 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004742 FromType = PT->getPointeeType();
4743
Douglas Gregor02824322011-01-26 19:30:28 +00004744 // When we had a pointer, it's implicitly dereferenced, so we
4745 // better have an lvalue.
4746 assert(FromClassification.isLValue());
4747 }
4748
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004749 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004750
Douglas Gregor02824322011-01-26 19:30:28 +00004751 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004752 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004753 // parameter is
4754 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004755 // - "lvalue reference to cv X" for functions declared without a
4756 // ref-qualifier or with the & ref-qualifier
4757 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004758 // ref-qualifier
4759 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004761 // cv-qualification on the member function declaration.
4762 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004763 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004764 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004765 // (C++ [over.match.funcs]p5). We perform a simplified version of
4766 // reference binding here, that allows class rvalues to bind to
4767 // non-constant references.
4768
Douglas Gregor02824322011-01-26 19:30:28 +00004769 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004770 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004771 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004772 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004773 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004774 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004775 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004776 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004777 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004778
4779 // Check that we have either the same type or a derived type. It
4780 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004781 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004782 ImplicitConversionKind SecondKind;
4783 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4784 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004785 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004786 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004787 else {
John McCall65eb8792010-02-25 01:37:24 +00004788 ICS.setBad(BadConversionSequence::unrelated_class,
4789 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004790 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004791 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004792
Douglas Gregor02824322011-01-26 19:30:28 +00004793 // Check the ref-qualifier.
4794 switch (Method->getRefQualifier()) {
4795 case RQ_None:
4796 // Do nothing; we don't care about lvalueness or rvalueness.
4797 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004798
Douglas Gregor02824322011-01-26 19:30:28 +00004799 case RQ_LValue:
4800 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4801 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004802 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004803 ImplicitParamType);
4804 return ICS;
4805 }
4806 break;
4807
4808 case RQ_RValue:
4809 if (!FromClassification.isRValue()) {
4810 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004811 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004812 ImplicitParamType);
4813 return ICS;
4814 }
4815 break;
4816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004817
Douglas Gregor436424c2008-11-18 23:14:02 +00004818 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004819 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004820 ICS.Standard.setAsIdentityConversion();
4821 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004822 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004823 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004824 ICS.Standard.ReferenceBinding = true;
4825 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004826 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004827 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004828 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4829 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4830 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004831 return ICS;
4832}
4833
4834/// PerformObjectArgumentInitialization - Perform initialization of
4835/// the implicit object parameter for the given Method with the given
4836/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004837ExprResult
4838Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004840 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004841 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004842 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004843 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004844 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004845
Douglas Gregor02824322011-01-26 19:30:28 +00004846 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004847 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004848 FromRecordType = PT->getPointeeType();
4849 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004850 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004851 } else {
4852 FromRecordType = From->getType();
4853 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004854 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004855 }
4856
John McCall6e9f8f62009-12-03 04:06:58 +00004857 // Note that we always use the true parent context when performing
4858 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004859 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4860 *this, From->getType(), FromClassification, Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004861 if (ICS.isBad()) {
4862 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4863 Qualifiers FromQs = FromRecordType.getQualifiers();
4864 Qualifiers ToQs = DestType.getQualifiers();
4865 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4866 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004867 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004868 diag::err_member_function_call_bad_cvr)
4869 << Method->getDeclName() << FromRecordType << (CVR - 1)
4870 << From->getSourceRange();
4871 Diag(Method->getLocation(), diag::note_previous_decl)
4872 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004873 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004874 }
4875 }
4876
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004877 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004878 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004879 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004880 }
Mike Stump11289f42009-09-09 15:08:12 +00004881
John Wiegley01296292011-04-08 18:41:53 +00004882 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4883 ExprResult FromRes =
4884 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4885 if (FromRes.isInvalid())
4886 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004887 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004888 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004889
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004890 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004891 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004892 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004893 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00004894}
4895
Douglas Gregor5fb53972009-01-14 15:45:31 +00004896/// TryContextuallyConvertToBool - Attempt to contextually convert the
4897/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004898static ImplicitConversionSequence
4899TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004900 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004901 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004902 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004903 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004904 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004905 /*AllowObjCWritebackConversion=*/false,
4906 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004907}
4908
4909/// PerformContextuallyConvertToBool - Perform a contextual conversion
4910/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004911ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004912 if (checkPlaceholderForOverload(*this, From))
4913 return ExprError();
4914
John McCall5c32be02010-08-24 20:38:10 +00004915 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004916 if (!ICS.isBad())
4917 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004918
Fariborz Jahanian76197412009-11-18 18:26:29 +00004919 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004920 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004921 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004922 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004923 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004924}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004925
Richard Smithf8379a02012-01-18 23:55:52 +00004926/// Check that the specified conversion is permitted in a converted constant
4927/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4928/// is acceptable.
4929static bool CheckConvertedConstantConversions(Sema &S,
4930 StandardConversionSequence &SCS) {
4931 // Since we know that the target type is an integral or unscoped enumeration
4932 // type, most conversion kinds are impossible. All possible First and Third
4933 // conversions are fine.
4934 switch (SCS.Second) {
4935 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00004936 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00004937 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00004938 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00004939 return true;
4940
4941 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004942 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00004943 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4944 // conversion, so we allow it in a converted constant expression.
4945 //
4946 // FIXME: Per core issue 1407, we should not allow this, but that breaks
4947 // a lot of popular code. We should at least add a warning for this
4948 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00004949 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4950 SCS.getToType(2)->isBooleanType();
4951
Richard Smith410cc892014-11-26 03:26:53 +00004952 case ICK_Pointer_Conversion:
4953 case ICK_Pointer_Member:
4954 // C++1z: null pointer conversions and null member pointer conversions are
4955 // only permitted if the source type is std::nullptr_t.
4956 return SCS.getFromType()->isNullPtrType();
4957
4958 case ICK_Floating_Promotion:
4959 case ICK_Complex_Promotion:
4960 case ICK_Floating_Conversion:
4961 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004962 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00004963 case ICK_Compatible_Conversion:
4964 case ICK_Derived_To_Base:
4965 case ICK_Vector_Conversion:
4966 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00004967 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00004968 case ICK_Block_Pointer_Conversion:
4969 case ICK_TransparentUnionConversion:
4970 case ICK_Writeback_Conversion:
4971 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004972 return false;
4973
4974 case ICK_Lvalue_To_Rvalue:
4975 case ICK_Array_To_Pointer:
4976 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00004977 llvm_unreachable("found a first conversion kind in Second");
4978
Richard Smithf8379a02012-01-18 23:55:52 +00004979 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00004980 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00004981
4982 case ICK_Num_Conversion_Kinds:
4983 break;
4984 }
4985
4986 llvm_unreachable("unknown conversion kind");
4987}
4988
4989/// CheckConvertedConstantExpression - Check that the expression From is a
4990/// converted constant expression of type T, perform the conversion and produce
4991/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00004992static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
4993 QualType T, APValue &Value,
4994 Sema::CCEKind CCE,
4995 bool RequireInt) {
4996 assert(S.getLangOpts().CPlusPlus11 &&
4997 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004998
Richard Smith410cc892014-11-26 03:26:53 +00004999 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005000 return ExprError();
5001
Richard Smith410cc892014-11-26 03:26:53 +00005002 // C++1z [expr.const]p3:
5003 // A converted constant expression of type T is an expression,
5004 // implicitly converted to type T, where the converted
5005 // expression is a constant expression and the implicit conversion
5006 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005007 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005008 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005009 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005010 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005011 /*AllowObjcWritebackConversion=*/false,
5012 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005013 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005014 switch (ICS.getKind()) {
5015 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005016 SCS = &ICS.Standard;
5017 break;
5018 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005019 // We are converting to a non-class type, so the Before sequence
5020 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005021 SCS = &ICS.UserDefined.After;
5022 break;
5023 case ImplicitConversionSequence::AmbiguousConversion:
5024 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005025 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5026 return S.Diag(From->getLocStart(),
5027 diag::err_typecheck_converted_constant_expression)
5028 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005029 return ExprError();
5030
5031 case ImplicitConversionSequence::EllipsisConversion:
5032 llvm_unreachable("ellipsis conversion in converted constant expression");
5033 }
5034
Richard Smith410cc892014-11-26 03:26:53 +00005035 // Check that we would only use permitted conversions.
5036 if (!CheckConvertedConstantConversions(S, *SCS)) {
5037 return S.Diag(From->getLocStart(),
5038 diag::err_typecheck_converted_constant_expression_disallowed)
5039 << From->getType() << From->getSourceRange() << T;
5040 }
5041 // [...] and where the reference binding (if any) binds directly.
5042 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5043 return S.Diag(From->getLocStart(),
5044 diag::err_typecheck_converted_constant_expression_indirect)
5045 << From->getType() << From->getSourceRange() << T;
5046 }
5047
5048 ExprResult Result =
5049 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005050 if (Result.isInvalid())
5051 return Result;
5052
5053 // Check for a narrowing implicit conversion.
5054 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005055 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005056 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005057 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005058 case NK_Variable_Narrowing:
5059 // Implicit conversion to a narrower type, and the value is not a constant
5060 // expression. We'll diagnose this in a moment.
5061 case NK_Not_Narrowing:
5062 break;
5063
5064 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005065 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005066 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005067 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005068 break;
5069
5070 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005071 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005072 << CCE << /*Constant*/0 << From->getType() << T;
5073 break;
5074 }
5075
5076 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005077 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005078 Expr::EvalResult Eval;
5079 Eval.Diag = &Notes;
5080
Richard Smith410cc892014-11-26 03:26:53 +00005081 if ((T->isReferenceType()
5082 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5083 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5084 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005085 // The expression can't be folded, so we can't keep it at this position in
5086 // the AST.
5087 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005088 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005089 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005090
5091 if (Notes.empty()) {
5092 // It's a constant expression.
5093 return Result;
5094 }
Richard Smithf8379a02012-01-18 23:55:52 +00005095 }
5096
5097 // It's not a constant expression. Produce an appropriate diagnostic.
5098 if (Notes.size() == 1 &&
5099 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005100 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005101 else {
Richard Smith410cc892014-11-26 03:26:53 +00005102 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005103 << CCE << From->getSourceRange();
5104 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005105 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005106 }
Richard Smith410cc892014-11-26 03:26:53 +00005107 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005108}
5109
Richard Smith410cc892014-11-26 03:26:53 +00005110ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5111 APValue &Value, CCEKind CCE) {
5112 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5113}
5114
5115ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5116 llvm::APSInt &Value,
5117 CCEKind CCE) {
5118 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5119
5120 APValue V;
5121 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5122 if (!R.isInvalid())
5123 Value = V.getInt();
5124 return R;
5125}
5126
5127
John McCallfec112d2011-09-09 06:11:02 +00005128/// dropPointerConversions - If the given standard conversion sequence
5129/// involves any pointer conversions, remove them. This may change
5130/// the result type of the conversion sequence.
5131static void dropPointerConversion(StandardConversionSequence &SCS) {
5132 if (SCS.Second == ICK_Pointer_Conversion) {
5133 SCS.Second = ICK_Identity;
5134 SCS.Third = ICK_Identity;
5135 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5136 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005137}
John McCall5c32be02010-08-24 20:38:10 +00005138
John McCallfec112d2011-09-09 06:11:02 +00005139/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5140/// convert the expression From to an Objective-C pointer type.
5141static ImplicitConversionSequence
5142TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5143 // Do an implicit conversion to 'id'.
5144 QualType Ty = S.Context.getObjCIdType();
5145 ImplicitConversionSequence ICS
5146 = TryImplicitConversion(S, From, Ty,
5147 // FIXME: Are these flags correct?
5148 /*SuppressUserConversions=*/false,
5149 /*AllowExplicit=*/true,
5150 /*InOverloadResolution=*/false,
5151 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005152 /*AllowObjCWritebackConversion=*/false,
5153 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005154
5155 // Strip off any final conversions to 'id'.
5156 switch (ICS.getKind()) {
5157 case ImplicitConversionSequence::BadConversion:
5158 case ImplicitConversionSequence::AmbiguousConversion:
5159 case ImplicitConversionSequence::EllipsisConversion:
5160 break;
5161
5162 case ImplicitConversionSequence::UserDefinedConversion:
5163 dropPointerConversion(ICS.UserDefined.After);
5164 break;
5165
5166 case ImplicitConversionSequence::StandardConversion:
5167 dropPointerConversion(ICS.Standard);
5168 break;
5169 }
5170
5171 return ICS;
5172}
5173
5174/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5175/// conversion of the expression From to an Objective-C pointer type.
5176ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005177 if (checkPlaceholderForOverload(*this, From))
5178 return ExprError();
5179
John McCall8b07ec22010-05-15 11:32:37 +00005180 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005181 ImplicitConversionSequence ICS =
5182 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005183 if (!ICS.isBad())
5184 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005185 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005186}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005187
Richard Smith8dd34252012-02-04 07:07:42 +00005188/// Determine whether the provided type is an integral type, or an enumeration
5189/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005190bool Sema::ICEConvertDiagnoser::match(QualType T) {
5191 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5192 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005193}
5194
Larisse Voufo236bec22013-06-10 06:50:24 +00005195static ExprResult
5196diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5197 Sema::ContextualImplicitConverter &Converter,
5198 QualType T, UnresolvedSetImpl &ViableConversions) {
5199
5200 if (Converter.Suppress)
5201 return ExprError();
5202
5203 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5204 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5205 CXXConversionDecl *Conv =
5206 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5207 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5208 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5209 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005210 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005211}
5212
5213static bool
5214diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5215 Sema::ContextualImplicitConverter &Converter,
5216 QualType T, bool HadMultipleCandidates,
5217 UnresolvedSetImpl &ExplicitConversions) {
5218 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5219 DeclAccessPair Found = ExplicitConversions[0];
5220 CXXConversionDecl *Conversion =
5221 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5222
5223 // The user probably meant to invoke the given explicit
5224 // conversion; use it.
5225 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5226 std::string TypeStr;
5227 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5228
5229 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5230 << FixItHint::CreateInsertion(From->getLocStart(),
5231 "static_cast<" + TypeStr + ">(")
5232 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005233 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005234 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5235
5236 // If we aren't in a SFINAE context, build a call to the
5237 // explicit conversion function.
5238 if (SemaRef.isSFINAEContext())
5239 return true;
5240
Craig Topperc3ec1492014-05-26 06:22:03 +00005241 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005242 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5243 HadMultipleCandidates);
5244 if (Result.isInvalid())
5245 return true;
5246 // Record usage of conversion in an implicit cast.
5247 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005248 CK_UserDefinedConversion, Result.get(),
5249 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005250 }
5251 return false;
5252}
5253
5254static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5255 Sema::ContextualImplicitConverter &Converter,
5256 QualType T, bool HadMultipleCandidates,
5257 DeclAccessPair &Found) {
5258 CXXConversionDecl *Conversion =
5259 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005260 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005261
5262 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5263 if (!Converter.SuppressConversion) {
5264 if (SemaRef.isSFINAEContext())
5265 return true;
5266
5267 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5268 << From->getSourceRange();
5269 }
5270
5271 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5272 HadMultipleCandidates);
5273 if (Result.isInvalid())
5274 return true;
5275 // Record usage of conversion in an implicit cast.
5276 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005277 CK_UserDefinedConversion, Result.get(),
5278 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005279 return false;
5280}
5281
5282static ExprResult finishContextualImplicitConversion(
5283 Sema &SemaRef, SourceLocation Loc, Expr *From,
5284 Sema::ContextualImplicitConverter &Converter) {
5285 if (!Converter.match(From->getType()) && !Converter.Suppress)
5286 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5287 << From->getSourceRange();
5288
5289 return SemaRef.DefaultLvalueConversion(From);
5290}
5291
5292static void
5293collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5294 UnresolvedSetImpl &ViableConversions,
5295 OverloadCandidateSet &CandidateSet) {
5296 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5297 DeclAccessPair FoundDecl = ViableConversions[I];
5298 NamedDecl *D = FoundDecl.getDecl();
5299 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5300 if (isa<UsingShadowDecl>(D))
5301 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5302
5303 CXXConversionDecl *Conv;
5304 FunctionTemplateDecl *ConvTemplate;
5305 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5306 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5307 else
5308 Conv = cast<CXXConversionDecl>(D);
5309
5310 if (ConvTemplate)
5311 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005312 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5313 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005314 else
5315 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005316 ToType, CandidateSet,
5317 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005318 }
5319}
5320
Richard Smithccc11812013-05-21 19:05:48 +00005321/// \brief Attempt to convert the given expression to a type which is accepted
5322/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005323///
Richard Smithccc11812013-05-21 19:05:48 +00005324/// This routine will attempt to convert an expression of class type to a
5325/// type accepted by the specified converter. In C++11 and before, the class
5326/// must have a single non-explicit conversion function converting to a matching
5327/// type. In C++1y, there can be multiple such conversion functions, but only
5328/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005329///
Douglas Gregor4799d032010-06-30 00:20:43 +00005330/// \param Loc The source location of the construct that requires the
5331/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005332///
James Dennett18348b62012-06-22 08:52:37 +00005333/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005334///
Richard Smithccc11812013-05-21 19:05:48 +00005335/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005336///
Douglas Gregor4799d032010-06-30 00:20:43 +00005337/// \returns The expression, converted to an integral or enumeration type if
5338/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005339ExprResult Sema::PerformContextualImplicitConversion(
5340 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005341 // We can't perform any more checking for type-dependent expressions.
5342 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005343 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005344
Eli Friedman1da70392012-01-26 00:26:18 +00005345 // Process placeholders immediately.
5346 if (From->hasPlaceholderType()) {
5347 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005348 if (result.isInvalid())
5349 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005350 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005351 }
5352
Richard Smithccc11812013-05-21 19:05:48 +00005353 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005354 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005355 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005356 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005357
5358 // FIXME: Check for missing '()' if T is a function type?
5359
Richard Smithccc11812013-05-21 19:05:48 +00005360 // We can only perform contextual implicit conversions on objects of class
5361 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005362 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005363 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005364 if (!Converter.Suppress)
5365 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005366 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005368
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005369 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005370 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005371 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005372 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005373
5374 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5375 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5376
Craig Toppere14c0f82014-03-12 04:55:44 +00005377 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005378 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005379 }
Richard Smithccc11812013-05-21 19:05:48 +00005380 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005381
5382 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005383 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005384
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005385 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005386 UnresolvedSet<4>
5387 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005388 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005389 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005390 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005391
Larisse Voufo236bec22013-06-10 06:50:24 +00005392 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005393 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005394
Larisse Voufo236bec22013-06-10 06:50:24 +00005395 // To check that there is only one target type, in C++1y:
5396 QualType ToType;
5397 bool HasUniqueTargetType = true;
5398
5399 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005400 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005401 NamedDecl *D = (*I)->getUnderlyingDecl();
5402 CXXConversionDecl *Conversion;
5403 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5404 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005405 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005406 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5407 else
5408 continue; // C++11 does not consider conversion operator templates(?).
5409 } else
5410 Conversion = cast<CXXConversionDecl>(D);
5411
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005412 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005413 "Conversion operator templates are considered potentially "
5414 "viable in C++1y");
5415
5416 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5417 if (Converter.match(CurToType) || ConvTemplate) {
5418
5419 if (Conversion->isExplicit()) {
5420 // FIXME: For C++1y, do we need this restriction?
5421 // cf. diagnoseNoViableConversion()
5422 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005423 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005424 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005425 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005426 if (ToType.isNull())
5427 ToType = CurToType.getUnqualifiedType();
5428 else if (HasUniqueTargetType &&
5429 (CurToType.getUnqualifiedType() != ToType))
5430 HasUniqueTargetType = false;
5431 }
5432 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005433 }
Richard Smith8dd34252012-02-04 07:07:42 +00005434 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005435 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005436
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005437 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005438 // C++1y [conv]p6:
5439 // ... An expression e of class type E appearing in such a context
5440 // is said to be contextually implicitly converted to a specified
5441 // type T and is well-formed if and only if e can be implicitly
5442 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005443 // for conversion functions whose return type is cv T or reference to
5444 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005445 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005446
Larisse Voufo236bec22013-06-10 06:50:24 +00005447 // If no unique T is found:
5448 if (ToType.isNull()) {
5449 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5450 HadMultipleCandidates,
5451 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005452 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005453 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005454 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005455
Larisse Voufo236bec22013-06-10 06:50:24 +00005456 // If more than one unique Ts are found:
5457 if (!HasUniqueTargetType)
5458 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5459 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005460
Larisse Voufo236bec22013-06-10 06:50:24 +00005461 // If one unique T is found:
5462 // First, build a candidate set from the previously recorded
5463 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005464 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005465 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5466 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005467
Larisse Voufo236bec22013-06-10 06:50:24 +00005468 // Then, perform overload resolution over the candidate set.
5469 OverloadCandidateSet::iterator Best;
5470 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5471 case OR_Success: {
5472 // Apply this conversion.
5473 DeclAccessPair Found =
5474 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5475 if (recordConversion(*this, Loc, From, Converter, T,
5476 HadMultipleCandidates, Found))
5477 return ExprError();
5478 break;
5479 }
5480 case OR_Ambiguous:
5481 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5482 ViableConversions);
5483 case OR_No_Viable_Function:
5484 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5485 HadMultipleCandidates,
5486 ExplicitConversions))
5487 return ExprError();
5488 // fall through 'OR_Deleted' case.
5489 case OR_Deleted:
5490 // We'll complain below about a non-integral condition type.
5491 break;
5492 }
5493 } else {
5494 switch (ViableConversions.size()) {
5495 case 0: {
5496 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5497 HadMultipleCandidates,
5498 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005499 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005500
Larisse Voufo236bec22013-06-10 06:50:24 +00005501 // We'll complain below about a non-integral condition type.
5502 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005503 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005504 case 1: {
5505 // Apply this conversion.
5506 DeclAccessPair Found = ViableConversions[0];
5507 if (recordConversion(*this, Loc, From, Converter, T,
5508 HadMultipleCandidates, Found))
5509 return ExprError();
5510 break;
5511 }
5512 default:
5513 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5514 ViableConversions);
5515 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005517
Larisse Voufo236bec22013-06-10 06:50:24 +00005518 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005519}
5520
Richard Smith100b24a2014-04-17 01:52:14 +00005521/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5522/// an acceptable non-member overloaded operator for a call whose
5523/// arguments have types T1 (and, if non-empty, T2). This routine
5524/// implements the check in C++ [over.match.oper]p3b2 concerning
5525/// enumeration types.
5526static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5527 FunctionDecl *Fn,
5528 ArrayRef<Expr *> Args) {
5529 QualType T1 = Args[0]->getType();
5530 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5531
5532 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5533 return true;
5534
5535 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5536 return true;
5537
5538 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5539 if (Proto->getNumParams() < 1)
5540 return false;
5541
5542 if (T1->isEnumeralType()) {
5543 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5544 if (Context.hasSameUnqualifiedType(T1, ArgType))
5545 return true;
5546 }
5547
5548 if (Proto->getNumParams() < 2)
5549 return false;
5550
5551 if (!T2.isNull() && T2->isEnumeralType()) {
5552 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5553 if (Context.hasSameUnqualifiedType(T2, ArgType))
5554 return true;
5555 }
5556
5557 return false;
5558}
5559
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005560/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005561/// candidate functions, using the given function call arguments. If
5562/// @p SuppressUserConversions, then don't allow user-defined
5563/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005564///
James Dennett2a4d13c2012-06-15 07:13:21 +00005565/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005566/// based on an incomplete set of function arguments. This feature is used by
5567/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005568void
5569Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005570 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005571 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005572 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005573 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005574 bool PartialOverloading,
5575 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005576 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005577 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005578 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005579 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005580 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005581
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005582 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005583 if (!isa<CXXConstructorDecl>(Method)) {
5584 // If we get here, it's because we're calling a member function
5585 // that is named without a member access expression (e.g.,
5586 // "this->f") that was either written explicitly or created
5587 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005588 // function, e.g., X::f(). We use an empty type for the implied
5589 // object argument (C++ [over.call.func]p3), and the acting context
5590 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005591 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005592 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005593 Args, CandidateSet, SuppressUserConversions,
5594 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005595 return;
5596 }
5597 // We treat a constructor like a non-member function, since its object
5598 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005599 }
5600
Douglas Gregorff7028a2009-11-13 23:59:09 +00005601 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005602 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005603
Richard Smith100b24a2014-04-17 01:52:14 +00005604 // C++ [over.match.oper]p3:
5605 // if no operand has a class type, only those non-member functions in the
5606 // lookup set that have a first parameter of type T1 or "reference to
5607 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5608 // is a right operand) a second parameter of type T2 or "reference to
5609 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5610 // candidate functions.
5611 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5612 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5613 return;
5614
Richard Smith8b86f2d2013-11-04 01:48:18 +00005615 // C++11 [class.copy]p11: [DR1402]
5616 // A defaulted move constructor that is defined as deleted is ignored by
5617 // overload resolution.
5618 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5619 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5620 Constructor->isMoveConstructor())
5621 return;
5622
Douglas Gregor27381f32009-11-23 12:27:39 +00005623 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005624 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005625
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005626 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005627 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005628 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005629 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005630 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005631 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005632 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005633 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005634
John McCall578a1f82014-12-14 01:46:53 +00005635 if (Constructor) {
5636 // C++ [class.copy]p3:
5637 // A member function template is never instantiated to perform the copy
5638 // of a class object to an object of its class type.
5639 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5640 if (Args.size() == 1 &&
5641 Constructor->isSpecializationCopyingObject() &&
5642 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5643 IsDerivedFrom(Args[0]->getType(), ClassType))) {
5644 Candidate.Viable = false;
5645 Candidate.FailureKind = ovl_fail_illegal_constructor;
5646 return;
5647 }
5648 }
5649
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005650 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005651
5652 // (C++ 13.3.2p2): A candidate function having fewer than m
5653 // parameters is viable only if it has an ellipsis in its parameter
5654 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005655 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005656 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005657 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005658 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005659 return;
5660 }
5661
5662 // (C++ 13.3.2p2): A candidate function having more than m parameters
5663 // is viable only if the (m+1)st parameter has a default argument
5664 // (8.3.6). For the purposes of overload resolution, the
5665 // parameter list is truncated on the right, so that there are
5666 // exactly m parameters.
5667 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005668 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005669 // Not enough arguments.
5670 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005671 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005672 return;
5673 }
5674
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005675 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005676 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005677 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005678 // Skip the check for callers that are implicit members, because in this
5679 // case we may not yet know what the member's target is; the target is
5680 // inferred for the member automatically, based on the bases and fields of
5681 // the class.
5682 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005683 Candidate.Viable = false;
5684 Candidate.FailureKind = ovl_fail_bad_target;
5685 return;
5686 }
5687
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005688 // Determine the implicit conversion sequences for each of the
5689 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005690 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005691 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005692 // (C++ 13.3.2p3): for F to be a viable function, there shall
5693 // exist for each argument an implicit conversion sequence
5694 // (13.3.3.1) that converts that argument to the corresponding
5695 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005696 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005697 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005698 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005699 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005700 /*InOverloadResolution=*/true,
5701 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005702 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005703 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005704 if (Candidate.Conversions[ArgIdx].isBad()) {
5705 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005706 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005707 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005708 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005709 } else {
5710 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5711 // argument for which there is no corresponding parameter is
5712 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005713 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005714 }
5715 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005716
5717 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5718 Candidate.Viable = false;
5719 Candidate.FailureKind = ovl_fail_enable_if;
5720 Candidate.DeductionFailure.Data = FailedAttr;
5721 return;
5722 }
5723}
5724
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005725ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005726 bool IsInstance) {
5727 SmallVector<ObjCMethodDecl*, 4> Methods;
5728 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5729 return nullptr;
5730
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005731 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5732 bool Match = true;
5733 ObjCMethodDecl *Method = Methods[b];
5734 unsigned NumNamedArgs = Sel.getNumArgs();
5735 // Method might have more arguments than selector indicates. This is due
5736 // to addition of c-style arguments in method.
5737 if (Method->param_size() > NumNamedArgs)
5738 NumNamedArgs = Method->param_size();
5739 if (Args.size() < NumNamedArgs)
5740 continue;
5741
5742 for (unsigned i = 0; i < NumNamedArgs; i++) {
5743 // We can't do any type-checking on a type-dependent argument.
5744 if (Args[i]->isTypeDependent()) {
5745 Match = false;
5746 break;
5747 }
5748
5749 ParmVarDecl *param = Method->parameters()[i];
5750 Expr *argExpr = Args[i];
5751 assert(argExpr && "SelectBestMethod(): missing expression");
5752
5753 // Strip the unbridged-cast placeholder expression off unless it's
5754 // a consumed argument.
5755 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5756 !param->hasAttr<CFConsumedAttr>())
5757 argExpr = stripARCUnbridgedCast(argExpr);
5758
5759 // If the parameter is __unknown_anytype, move on to the next method.
5760 if (param->getType() == Context.UnknownAnyTy) {
5761 Match = false;
5762 break;
5763 }
5764
5765 ImplicitConversionSequence ConversionState
5766 = TryCopyInitialization(*this, argExpr, param->getType(),
5767 /*SuppressUserConversions*/false,
5768 /*InOverloadResolution=*/true,
5769 /*AllowObjCWritebackConversion=*/
5770 getLangOpts().ObjCAutoRefCount,
5771 /*AllowExplicit*/false);
5772 if (ConversionState.isBad()) {
5773 Match = false;
5774 break;
5775 }
5776 }
5777 // Promote additional arguments to variadic methods.
5778 if (Match && Method->isVariadic()) {
5779 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5780 if (Args[i]->isTypeDependent()) {
5781 Match = false;
5782 break;
5783 }
5784 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5785 nullptr);
5786 if (Arg.isInvalid()) {
5787 Match = false;
5788 break;
5789 }
5790 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005791 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005792 // Check for extra arguments to non-variadic methods.
5793 if (Args.size() != NumNamedArgs)
5794 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005795 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5796 // Special case when selectors have no argument. In this case, select
5797 // one with the most general result type of 'id'.
5798 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5799 QualType ReturnT = Methods[b]->getReturnType();
5800 if (ReturnT->isObjCIdType())
5801 return Methods[b];
5802 }
5803 }
5804 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005805
5806 if (Match)
5807 return Method;
5808 }
5809 return nullptr;
5810}
5811
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005812static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5813
5814EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5815 bool MissingImplicitThis) {
5816 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5817 // we need to find the first failing one.
5818 if (!Function->hasAttrs())
Craig Topperc3ec1492014-05-26 06:22:03 +00005819 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005820 AttrVec Attrs = Function->getAttrs();
5821 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5822 IsNotEnableIfAttr);
5823 if (Attrs.begin() == E)
Craig Topperc3ec1492014-05-26 06:22:03 +00005824 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005825 std::reverse(Attrs.begin(), E);
5826
5827 SFINAETrap Trap(*this);
5828
5829 // Convert the arguments.
5830 SmallVector<Expr *, 16> ConvertedArgs;
5831 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005832 bool ContainsValueDependentExpr = false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005833 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5834 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005835 !cast<CXXMethodDecl>(Function)->isStatic() &&
5836 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005837 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5838 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005839 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005840 Method, Method);
5841 if (R.isInvalid()) {
5842 InitializationFailed = true;
5843 break;
5844 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005845 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005846 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005847 } else {
5848 ExprResult R =
5849 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5850 Context,
5851 Function->getParamDecl(i)),
5852 SourceLocation(),
5853 Args[i]);
5854 if (R.isInvalid()) {
5855 InitializationFailed = true;
5856 break;
5857 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005858 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005859 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005860 }
5861 }
5862
5863 if (InitializationFailed || Trap.hasErrorOccurred())
5864 return cast<EnableIfAttr>(Attrs[0]);
5865
5866 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5867 APValue Result;
5868 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005869 if (EIA->getCond()->isValueDependent()) {
5870 // Don't even try now, we'll examine it after instantiation.
5871 continue;
5872 }
5873
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005874 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005875 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5876 if (!ContainsValueDependentExpr)
5877 return EIA;
5878 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005879 return EIA;
5880 }
5881 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005882 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005883}
5884
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005885/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005886/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005887void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005888 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005889 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005890 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005891 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005892 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00005893 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005894 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5895 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005896 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005897 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005898 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005899 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005900 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005901 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005902 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005903 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005904 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005905 } else {
John McCalla0296f72010-03-19 07:35:19 +00005906 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005907 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5908 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005909 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005910 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005911 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005912 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005913 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005914 CandidateSet, SuppressUserConversions,
5915 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005916 else
John McCalla0296f72010-03-19 07:35:19 +00005917 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005918 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005919 CandidateSet, SuppressUserConversions,
5920 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005921 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005922 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005923}
5924
John McCallf0f1cf02009-11-17 07:50:12 +00005925/// AddMethodCandidate - Adds a named decl (which is some kind of
5926/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005927void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005928 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005929 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005930 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005931 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005932 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005933 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005934 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005935
5936 if (isa<UsingShadowDecl>(Decl))
5937 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005938
John McCallf0f1cf02009-11-17 07:50:12 +00005939 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5940 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5941 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005942 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00005943 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005944 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005945 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005946 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005947 } else {
John McCalla0296f72010-03-19 07:35:19 +00005948 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005949 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005950 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005951 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005952 }
5953}
5954
Douglas Gregor436424c2008-11-18 23:14:02 +00005955/// AddMethodCandidate - Adds the given C++ member function to the set
5956/// of candidate functions, using the given function call arguments
5957/// and the object argument (@c Object). For example, in a call
5958/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5959/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5960/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005961/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005962void
John McCalla0296f72010-03-19 07:35:19 +00005963Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005964 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005965 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005966 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005967 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005968 bool SuppressUserConversions,
5969 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005970 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005971 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005972 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005973 assert(!isa<CXXConstructorDecl>(Method) &&
5974 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005975
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005976 if (!CandidateSet.isNewCandidate(Method))
5977 return;
5978
Richard Smith8b86f2d2013-11-04 01:48:18 +00005979 // C++11 [class.copy]p23: [DR1402]
5980 // A defaulted move assignment operator that is defined as deleted is
5981 // ignored by overload resolution.
5982 if (Method->isDefaulted() && Method->isDeleted() &&
5983 Method->isMoveAssignmentOperator())
5984 return;
5985
Douglas Gregor27381f32009-11-23 12:27:39 +00005986 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005987 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005988
Douglas Gregor436424c2008-11-18 23:14:02 +00005989 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005990 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005991 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005992 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005993 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005994 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005995 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005996
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005997 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00005998
5999 // (C++ 13.3.2p2): A candidate function having fewer than m
6000 // parameters is viable only if it has an ellipsis in its parameter
6001 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006002 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6003 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006004 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006005 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006006 return;
6007 }
6008
6009 // (C++ 13.3.2p2): A candidate function having more than m parameters
6010 // is viable only if the (m+1)st parameter has a default argument
6011 // (8.3.6). For the purposes of overload resolution, the
6012 // parameter list is truncated on the right, so that there are
6013 // exactly m parameters.
6014 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006015 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006016 // Not enough arguments.
6017 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006018 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006019 return;
6020 }
6021
6022 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006023
John McCall6e9f8f62009-12-03 04:06:58 +00006024 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006025 // The implicit object argument is ignored.
6026 Candidate.IgnoreObjectArgument = true;
6027 else {
6028 // Determine the implicit conversion sequence for the object
6029 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00006030 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00006031 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6032 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006033 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006034 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006035 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006036 return;
6037 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006038 }
6039
Eli Bendersky291a57e2014-09-25 23:59:08 +00006040 // (CUDA B.1): Check for invalid calls between targets.
6041 if (getLangOpts().CUDA)
6042 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6043 if (CheckCUDATarget(Caller, Method)) {
6044 Candidate.Viable = false;
6045 Candidate.FailureKind = ovl_fail_bad_target;
6046 return;
6047 }
6048
Douglas Gregor436424c2008-11-18 23:14:02 +00006049 // Determine the implicit conversion sequences for each of the
6050 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006051 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006052 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006053 // (C++ 13.3.2p3): for F to be a viable function, there shall
6054 // exist for each argument an implicit conversion sequence
6055 // (13.3.3.1) that converts that argument to the corresponding
6056 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006057 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006058 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006059 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006060 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006061 /*InOverloadResolution=*/true,
6062 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006063 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006064 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006065 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006066 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006067 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006068 }
6069 } else {
6070 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6071 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006072 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006073 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006074 }
6075 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006076
6077 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6078 Candidate.Viable = false;
6079 Candidate.FailureKind = ovl_fail_enable_if;
6080 Candidate.DeductionFailure.Data = FailedAttr;
6081 return;
6082 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006083}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006084
Douglas Gregor97628d62009-08-21 00:16:32 +00006085/// \brief Add a C++ member function template as a candidate to the candidate
6086/// set, using template argument deduction to produce an appropriate member
6087/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006088void
Douglas Gregor97628d62009-08-21 00:16:32 +00006089Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006090 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006091 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006092 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006093 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006094 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006095 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006096 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006097 bool SuppressUserConversions,
6098 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006099 if (!CandidateSet.isNewCandidate(MethodTmpl))
6100 return;
6101
Douglas Gregor97628d62009-08-21 00:16:32 +00006102 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006103 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006104 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006105 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006106 // candidate functions in the usual way.113) A given name can refer to one
6107 // or more function templates and also to a set of overloaded non-template
6108 // functions. In such a case, the candidate functions generated from each
6109 // function template are combined with the set of non-template candidate
6110 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006111 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006112 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006113 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006114 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006115 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006116 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006117 Candidate.FoundDecl = FoundDecl;
6118 Candidate.Function = MethodTmpl->getTemplatedDecl();
6119 Candidate.Viable = false;
6120 Candidate.FailureKind = ovl_fail_bad_deduction;
6121 Candidate.IsSurrogate = false;
6122 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006123 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006124 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006125 Info);
6126 return;
6127 }
Mike Stump11289f42009-09-09 15:08:12 +00006128
Douglas Gregor97628d62009-08-21 00:16:32 +00006129 // Add the function template specialization produced by template argument
6130 // deduction as a candidate.
6131 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006132 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006133 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006134 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006135 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006136 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006137}
6138
Douglas Gregor05155d82009-08-21 23:19:43 +00006139/// \brief Add a C++ function template specialization as a candidate
6140/// in the candidate set, using template argument deduction to produce
6141/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006142void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006143Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006144 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006145 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006146 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006147 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006148 bool SuppressUserConversions,
6149 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006150 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6151 return;
6152
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006153 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006154 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006155 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006156 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006157 // candidate functions in the usual way.113) A given name can refer to one
6158 // or more function templates and also to a set of overloaded non-template
6159 // functions. In such a case, the candidate functions generated from each
6160 // function template are combined with the set of non-template candidate
6161 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006162 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006163 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006164 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006165 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006166 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006167 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006168 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006169 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6170 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006171 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006172 Candidate.IsSurrogate = false;
6173 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006174 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006175 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006176 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006177 return;
6178 }
Mike Stump11289f42009-09-09 15:08:12 +00006179
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006180 // Add the function template specialization produced by template argument
6181 // deduction as a candidate.
6182 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006183 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006184 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006185}
Mike Stump11289f42009-09-09 15:08:12 +00006186
Douglas Gregor4b60a152013-11-07 22:34:54 +00006187/// Determine whether this is an allowable conversion from the result
6188/// of an explicit conversion operator to the expected type, per C++
6189/// [over.match.conv]p1 and [over.match.ref]p1.
6190///
6191/// \param ConvType The return type of the conversion function.
6192///
6193/// \param ToType The type we are converting to.
6194///
6195/// \param AllowObjCPointerConversion Allow a conversion from one
6196/// Objective-C pointer to another.
6197///
6198/// \returns true if the conversion is allowable, false otherwise.
6199static bool isAllowableExplicitConversion(Sema &S,
6200 QualType ConvType, QualType ToType,
6201 bool AllowObjCPointerConversion) {
6202 QualType ToNonRefType = ToType.getNonReferenceType();
6203
6204 // Easy case: the types are the same.
6205 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6206 return true;
6207
6208 // Allow qualification conversions.
6209 bool ObjCLifetimeConversion;
6210 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6211 ObjCLifetimeConversion))
6212 return true;
6213
6214 // If we're not allowed to consider Objective-C pointer conversions,
6215 // we're done.
6216 if (!AllowObjCPointerConversion)
6217 return false;
6218
6219 // Is this an Objective-C pointer conversion?
6220 bool IncompatibleObjC = false;
6221 QualType ConvertedType;
6222 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6223 IncompatibleObjC);
6224}
6225
Douglas Gregora1f013e2008-11-07 22:36:19 +00006226/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006227/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006228/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006229/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006230/// (which may or may not be the same type as the type that the
6231/// conversion function produces).
6232void
6233Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006234 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006235 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006236 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006237 OverloadCandidateSet& CandidateSet,
6238 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006239 assert(!Conversion->getDescribedFunctionTemplate() &&
6240 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006241 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006242 if (!CandidateSet.isNewCandidate(Conversion))
6243 return;
6244
Richard Smith2a7d4812013-05-04 07:00:32 +00006245 // If the conversion function has an undeduced return type, trigger its
6246 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006247 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006248 if (DeduceReturnType(Conversion, From->getExprLoc()))
6249 return;
6250 ConvType = Conversion->getConversionType().getNonReferenceType();
6251 }
6252
Richard Smith089c3162013-09-21 21:55:46 +00006253 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6254 // operator is only a candidate if its return type is the target type or
6255 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006256 if (Conversion->isExplicit() &&
6257 !isAllowableExplicitConversion(*this, ConvType, ToType,
6258 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006259 return;
6260
Douglas Gregor27381f32009-11-23 12:27:39 +00006261 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006262 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006263
Douglas Gregora1f013e2008-11-07 22:36:19 +00006264 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006265 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006266 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006267 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006268 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006269 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006270 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006271 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006272 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006273 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006274 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006275
Douglas Gregor6affc782010-08-19 15:37:02 +00006276 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006277 // For conversion functions, the function is considered to be a member of
6278 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006279 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006280 //
6281 // Determine the implicit conversion sequence for the implicit
6282 // object parameter.
6283 QualType ImplicitParamType = From->getType();
6284 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6285 ImplicitParamType = FromPtrType->getPointeeType();
6286 CXXRecordDecl *ConversionContext
6287 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006288
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006289 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006290 = TryObjectArgumentInitialization(*this, From->getType(),
6291 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006292 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006293
John McCall0d1da222010-01-12 00:44:57 +00006294 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006295 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006296 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006297 return;
6298 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006299
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006300 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006301 // derived to base as such conversions are given Conversion Rank. They only
6302 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6303 QualType FromCanon
6304 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6305 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6306 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6307 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006308 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006309 return;
6310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006311
Douglas Gregora1f013e2008-11-07 22:36:19 +00006312 // To determine what the conversion from the result of calling the
6313 // conversion function to the type we're eventually trying to
6314 // convert to (ToType), we need to synthesize a call to the
6315 // conversion function and attempt copy initialization from it. This
6316 // makes sure that we get the right semantics with respect to
6317 // lvalues/rvalues and the type. Fortunately, we can allocate this
6318 // call on the stack and we don't need its arguments to be
6319 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006320 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006321 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006322 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6323 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006324 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006325 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006326
Richard Smith48d24642011-07-13 22:53:21 +00006327 QualType ConversionType = Conversion->getConversionType();
6328 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006329 Candidate.Viable = false;
6330 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6331 return;
6332 }
6333
Richard Smith48d24642011-07-13 22:53:21 +00006334 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006335
Mike Stump11289f42009-09-09 15:08:12 +00006336 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006337 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6338 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006339 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006340 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006341 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006342 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006343 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006344 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006345 /*InOverloadResolution=*/false,
6346 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006347
John McCall0d1da222010-01-12 00:44:57 +00006348 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006349 case ImplicitConversionSequence::StandardConversion:
6350 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006351
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006352 // C++ [over.ics.user]p3:
6353 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006354 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006355 // shall have exact match rank.
6356 if (Conversion->getPrimaryTemplate() &&
6357 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6358 Candidate.Viable = false;
6359 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006360 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006361 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006362
Douglas Gregorcba72b12011-01-21 05:18:22 +00006363 // C++0x [dcl.init.ref]p5:
6364 // In the second case, if the reference is an rvalue reference and
6365 // the second standard conversion sequence of the user-defined
6366 // conversion sequence includes an lvalue-to-rvalue conversion, the
6367 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006368 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006369 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6370 Candidate.Viable = false;
6371 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006372 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006373 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006374 break;
6375
6376 case ImplicitConversionSequence::BadConversion:
6377 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006378 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006379 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006380
6381 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006382 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006383 "Can only end up with a standard conversion sequence or failure");
6384 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006385
Craig Topper5fc8fc22014-08-27 06:28:36 +00006386 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006387 Candidate.Viable = false;
6388 Candidate.FailureKind = ovl_fail_enable_if;
6389 Candidate.DeductionFailure.Data = FailedAttr;
6390 return;
6391 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006392}
6393
Douglas Gregor05155d82009-08-21 23:19:43 +00006394/// \brief Adds a conversion function template specialization
6395/// candidate to the overload set, using template argument deduction
6396/// to deduce the template arguments of the conversion function
6397/// template from the type that we are converting to (C++
6398/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006399void
Douglas Gregor05155d82009-08-21 23:19:43 +00006400Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006401 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006402 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006403 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006404 OverloadCandidateSet &CandidateSet,
6405 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006406 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6407 "Only conversion function templates permitted here");
6408
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006409 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6410 return;
6411
Craig Toppere6706e42012-09-19 02:26:47 +00006412 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006413 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006414 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006415 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006416 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006417 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006418 Candidate.FoundDecl = FoundDecl;
6419 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6420 Candidate.Viable = false;
6421 Candidate.FailureKind = ovl_fail_bad_deduction;
6422 Candidate.IsSurrogate = false;
6423 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006424 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006425 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006426 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006427 return;
6428 }
Mike Stump11289f42009-09-09 15:08:12 +00006429
Douglas Gregor05155d82009-08-21 23:19:43 +00006430 // Add the conversion function template specialization produced by
6431 // template argument deduction as a candidate.
6432 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006433 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006434 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006435}
6436
Douglas Gregorab7897a2008-11-19 22:57:39 +00006437/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6438/// converts the given @c Object to a function pointer via the
6439/// conversion function @c Conversion, and then attempts to call it
6440/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6441/// the type of function that we'll eventually be calling.
6442void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006443 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006444 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006445 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006446 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006447 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006448 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006449 if (!CandidateSet.isNewCandidate(Conversion))
6450 return;
6451
Douglas Gregor27381f32009-11-23 12:27:39 +00006452 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006453 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006454
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006455 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006456 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006457 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006458 Candidate.Surrogate = Conversion;
6459 Candidate.Viable = true;
6460 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006461 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006462 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006463
6464 // Determine the implicit conversion sequence for the implicit
6465 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006466 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006467 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006468 Object->Classify(Context),
6469 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006470 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006471 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006472 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006473 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006474 return;
6475 }
6476
6477 // The first conversion is actually a user-defined conversion whose
6478 // first conversion is ObjectInit's standard conversion (which is
6479 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006480 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006481 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006482 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006483 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006484 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006485 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006486 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006487 = Candidate.Conversions[0].UserDefined.Before;
6488 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6489
Mike Stump11289f42009-09-09 15:08:12 +00006490 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006491 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006492
6493 // (C++ 13.3.2p2): A candidate function having fewer than m
6494 // parameters is viable only if it has an ellipsis in its parameter
6495 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006496 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006497 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006498 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006499 return;
6500 }
6501
6502 // Function types don't have any default arguments, so just check if
6503 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006504 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006505 // Not enough arguments.
6506 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006507 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006508 return;
6509 }
6510
6511 // Determine the implicit conversion sequences for each of the
6512 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006513 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006514 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006515 // (C++ 13.3.2p3): for F to be a viable function, there shall
6516 // exist for each argument an implicit conversion sequence
6517 // (13.3.3.1) that converts that argument to the corresponding
6518 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006519 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006520 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006521 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006522 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006523 /*InOverloadResolution=*/false,
6524 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006525 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006526 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006527 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006528 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006529 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006530 }
6531 } else {
6532 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6533 // argument for which there is no corresponding parameter is
6534 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006535 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006536 }
6537 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006538
Craig Topper5fc8fc22014-08-27 06:28:36 +00006539 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006540 Candidate.Viable = false;
6541 Candidate.FailureKind = ovl_fail_enable_if;
6542 Candidate.DeductionFailure.Data = FailedAttr;
6543 return;
6544 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006545}
6546
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006547/// \brief Add overload candidates for overloaded operators that are
6548/// member functions.
6549///
6550/// Add the overloaded operator candidates that are member functions
6551/// for the operator Op that was used in an operator expression such
6552/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6553/// CandidateSet will store the added overload candidates. (C++
6554/// [over.match.oper]).
6555void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6556 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006557 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006558 OverloadCandidateSet& CandidateSet,
6559 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006560 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6561
6562 // C++ [over.match.oper]p3:
6563 // For a unary operator @ with an operand of a type whose
6564 // cv-unqualified version is T1, and for a binary operator @ with
6565 // a left operand of a type whose cv-unqualified version is T1 and
6566 // a right operand of a type whose cv-unqualified version is T2,
6567 // three sets of candidate functions, designated member
6568 // candidates, non-member candidates and built-in candidates, are
6569 // constructed as follows:
6570 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006571
Richard Smith0feaf0c2013-04-20 12:41:22 +00006572 // -- If T1 is a complete class type or a class currently being
6573 // defined, the set of member candidates is the result of the
6574 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6575 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006576 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006577 // Complete the type if it can be completed.
6578 RequireCompleteType(OpLoc, T1, 0);
6579 // If the type is neither complete nor being defined, bail out now.
6580 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006581 return;
Mike Stump11289f42009-09-09 15:08:12 +00006582
John McCall27b18f82009-11-17 02:14:36 +00006583 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6584 LookupQualifiedName(Operators, T1Rec->getDecl());
6585 Operators.suppressDiagnostics();
6586
Mike Stump11289f42009-09-09 15:08:12 +00006587 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006588 OperEnd = Operators.end();
6589 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006590 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006591 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006592 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006593 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006594 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006595 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006596 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006597}
6598
Douglas Gregora11693b2008-11-12 17:17:38 +00006599/// AddBuiltinCandidate - Add a candidate for a built-in
6600/// operator. ResultTy and ParamTys are the result and parameter types
6601/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006602/// arguments being passed to the candidate. IsAssignmentOperator
6603/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006604/// operator. NumContextualBoolArguments is the number of arguments
6605/// (at the beginning of the argument list) that will be contextually
6606/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006607void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006608 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006609 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006610 bool IsAssignmentOperator,
6611 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006612 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006613 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006614
Douglas Gregora11693b2008-11-12 17:17:38 +00006615 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006616 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006617 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6618 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006619 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006620 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006621 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006622 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006623 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6624
6625 // Determine the implicit conversion sequences for each of the
6626 // arguments.
6627 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006628 Candidate.ExplicitCallArguments = Args.size();
6629 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006630 // C++ [over.match.oper]p4:
6631 // For the built-in assignment operators, conversions of the
6632 // left operand are restricted as follows:
6633 // -- no temporaries are introduced to hold the left operand, and
6634 // -- no user-defined conversions are applied to the left
6635 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006636 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006637 //
6638 // We block these conversions by turning off user-defined
6639 // conversions, since that is the only way that initialization of
6640 // a reference to a non-class type can occur from something that
6641 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006642 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006643 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006644 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006645 Candidate.Conversions[ArgIdx]
6646 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006647 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006648 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006649 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006650 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006651 /*InOverloadResolution=*/false,
6652 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006653 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006654 }
John McCall0d1da222010-01-12 00:44:57 +00006655 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006656 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006657 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006658 break;
6659 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006660 }
6661}
6662
Craig Toppercd7b0332013-07-01 06:29:40 +00006663namespace {
6664
Douglas Gregora11693b2008-11-12 17:17:38 +00006665/// BuiltinCandidateTypeSet - A set of types that will be used for the
6666/// candidate operator functions for built-in operators (C++
6667/// [over.built]). The types are separated into pointer types and
6668/// enumeration types.
6669class BuiltinCandidateTypeSet {
6670 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006671 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006672
6673 /// PointerTypes - The set of pointer types that will be used in the
6674 /// built-in candidates.
6675 TypeSet PointerTypes;
6676
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006677 /// MemberPointerTypes - The set of member pointer types that will be
6678 /// used in the built-in candidates.
6679 TypeSet MemberPointerTypes;
6680
Douglas Gregora11693b2008-11-12 17:17:38 +00006681 /// EnumerationTypes - The set of enumeration types that will be
6682 /// used in the built-in candidates.
6683 TypeSet EnumerationTypes;
6684
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006685 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006686 /// candidates.
6687 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006688
6689 /// \brief A flag indicating non-record types are viable candidates
6690 bool HasNonRecordTypes;
6691
6692 /// \brief A flag indicating whether either arithmetic or enumeration types
6693 /// were present in the candidate set.
6694 bool HasArithmeticOrEnumeralTypes;
6695
Douglas Gregor80af3132011-05-21 23:15:46 +00006696 /// \brief A flag indicating whether the nullptr type was present in the
6697 /// candidate set.
6698 bool HasNullPtrType;
6699
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006700 /// Sema - The semantic analysis instance where we are building the
6701 /// candidate type set.
6702 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006703
Douglas Gregora11693b2008-11-12 17:17:38 +00006704 /// Context - The AST context in which we will build the type sets.
6705 ASTContext &Context;
6706
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006707 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6708 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006709 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006710
6711public:
6712 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006713 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006714
Mike Stump11289f42009-09-09 15:08:12 +00006715 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006716 : HasNonRecordTypes(false),
6717 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006718 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006719 SemaRef(SemaRef),
6720 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006721
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006722 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006723 SourceLocation Loc,
6724 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006725 bool AllowExplicitConversions,
6726 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006727
6728 /// pointer_begin - First pointer type found;
6729 iterator pointer_begin() { return PointerTypes.begin(); }
6730
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006731 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006732 iterator pointer_end() { return PointerTypes.end(); }
6733
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006734 /// member_pointer_begin - First member pointer type found;
6735 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6736
6737 /// member_pointer_end - Past the last member pointer type found;
6738 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6739
Douglas Gregora11693b2008-11-12 17:17:38 +00006740 /// enumeration_begin - First enumeration type found;
6741 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6742
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006743 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006744 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006745
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006746 iterator vector_begin() { return VectorTypes.begin(); }
6747 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006748
6749 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6750 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006751 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006752};
6753
Craig Toppercd7b0332013-07-01 06:29:40 +00006754} // end anonymous namespace
6755
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006756/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006757/// the set of pointer types along with any more-qualified variants of
6758/// that type. For example, if @p Ty is "int const *", this routine
6759/// will add "int const *", "int const volatile *", "int const
6760/// restrict *", and "int const volatile restrict *" to the set of
6761/// pointer types. Returns true if the add of @p Ty itself succeeded,
6762/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006763///
6764/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006765bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006766BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6767 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006768
Douglas Gregora11693b2008-11-12 17:17:38 +00006769 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006770 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006771 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006772
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006773 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006774 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006775 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006776 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006777 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6778 PointeeTy = PTy->getPointeeType();
6779 buildObjCPtr = true;
6780 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006781 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006782 }
6783
Sebastian Redl4990a632009-11-18 20:39:26 +00006784 // Don't add qualified variants of arrays. For one, they're not allowed
6785 // (the qualifier would sink to the element type), and for another, the
6786 // only overload situation where it matters is subscript or pointer +- int,
6787 // and those shouldn't have qualifier variants anyway.
6788 if (PointeeTy->isArrayType())
6789 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006790
John McCall8ccfcb52009-09-24 19:53:00 +00006791 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006792 bool hasVolatile = VisibleQuals.hasVolatile();
6793 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006794
John McCall8ccfcb52009-09-24 19:53:00 +00006795 // Iterate through all strict supersets of BaseCVR.
6796 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6797 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006798 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006799 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006800
6801 // Skip over restrict if no restrict found anywhere in the types, or if
6802 // the type cannot be restrict-qualified.
6803 if ((CVR & Qualifiers::Restrict) &&
6804 (!hasRestrict ||
6805 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6806 continue;
6807
6808 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006809 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006810
6811 // Build qualified pointer type.
6812 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006813 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006814 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006815 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006816 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6817
6818 // Insert qualified pointer type.
6819 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006820 }
6821
6822 return true;
6823}
6824
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006825/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6826/// to the set of pointer types along with any more-qualified variants of
6827/// that type. For example, if @p Ty is "int const *", this routine
6828/// will add "int const *", "int const volatile *", "int const
6829/// restrict *", and "int const volatile restrict *" to the set of
6830/// pointer types. Returns true if the add of @p Ty itself succeeded,
6831/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006832///
6833/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006834bool
6835BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6836 QualType Ty) {
6837 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006838 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006839 return false;
6840
John McCall8ccfcb52009-09-24 19:53:00 +00006841 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6842 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006843
John McCall8ccfcb52009-09-24 19:53:00 +00006844 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006845 // Don't add qualified variants of arrays. For one, they're not allowed
6846 // (the qualifier would sink to the element type), and for another, the
6847 // only overload situation where it matters is subscript or pointer +- int,
6848 // and those shouldn't have qualifier variants anyway.
6849 if (PointeeTy->isArrayType())
6850 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006851 const Type *ClassTy = PointerTy->getClass();
6852
6853 // Iterate through all strict supersets of the pointee type's CVR
6854 // qualifiers.
6855 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6856 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6857 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006858
John McCall8ccfcb52009-09-24 19:53:00 +00006859 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006860 MemberPointerTypes.insert(
6861 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006862 }
6863
6864 return true;
6865}
6866
Douglas Gregora11693b2008-11-12 17:17:38 +00006867/// AddTypesConvertedFrom - Add each of the types to which the type @p
6868/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006869/// primarily interested in pointer types and enumeration types. We also
6870/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006871/// AllowUserConversions is true if we should look at the conversion
6872/// functions of a class type, and AllowExplicitConversions if we
6873/// should also include the explicit conversion functions of a class
6874/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006875void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006876BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006877 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006878 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006879 bool AllowExplicitConversions,
6880 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006881 // Only deal with canonical types.
6882 Ty = Context.getCanonicalType(Ty);
6883
6884 // Look through reference types; they aren't part of the type of an
6885 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006886 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006887 Ty = RefTy->getPointeeType();
6888
John McCall33ddac02011-01-19 10:06:00 +00006889 // If we're dealing with an array type, decay to the pointer.
6890 if (Ty->isArrayType())
6891 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6892
6893 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006894 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006895
Chandler Carruth00a38332010-12-13 01:44:01 +00006896 // Flag if we ever add a non-record type.
6897 const RecordType *TyRec = Ty->getAs<RecordType>();
6898 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6899
Chandler Carruth00a38332010-12-13 01:44:01 +00006900 // Flag if we encounter an arithmetic type.
6901 HasArithmeticOrEnumeralTypes =
6902 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6903
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006904 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6905 PointerTypes.insert(Ty);
6906 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006907 // Insert our type, and its more-qualified variants, into the set
6908 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006909 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006910 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006911 } else if (Ty->isMemberPointerType()) {
6912 // Member pointers are far easier, since the pointee can't be converted.
6913 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6914 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006915 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006916 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006917 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006918 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006919 // We treat vector types as arithmetic types in many contexts as an
6920 // extension.
6921 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006922 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006923 } else if (Ty->isNullPtrType()) {
6924 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006925 } else if (AllowUserConversions && TyRec) {
6926 // No conversion functions in incomplete types.
6927 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6928 return;
Mike Stump11289f42009-09-09 15:08:12 +00006929
Chandler Carruth00a38332010-12-13 01:44:01 +00006930 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00006931 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006932 if (isa<UsingShadowDecl>(D))
6933 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006934
Chandler Carruth00a38332010-12-13 01:44:01 +00006935 // Skip conversion function templates; they don't tell us anything
6936 // about which builtin types we can convert to.
6937 if (isa<FunctionTemplateDecl>(D))
6938 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006939
Chandler Carruth00a38332010-12-13 01:44:01 +00006940 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6941 if (AllowExplicitConversions || !Conv->isExplicit()) {
6942 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6943 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006944 }
6945 }
6946 }
6947}
6948
Douglas Gregor84605ae2009-08-24 13:43:27 +00006949/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6950/// the volatile- and non-volatile-qualified assignment operators for the
6951/// given type to the candidate set.
6952static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6953 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006954 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006955 OverloadCandidateSet &CandidateSet) {
6956 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006957
Douglas Gregor84605ae2009-08-24 13:43:27 +00006958 // T& operator=(T&, T)
6959 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6960 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006961 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006962 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006963
Douglas Gregor84605ae2009-08-24 13:43:27 +00006964 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6965 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006966 ParamTypes[0]
6967 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006968 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006969 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006970 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006971 }
6972}
Mike Stump11289f42009-09-09 15:08:12 +00006973
Sebastian Redl1054fae2009-10-25 17:03:50 +00006974/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6975/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006976static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6977 Qualifiers VRQuals;
6978 const RecordType *TyRec;
6979 if (const MemberPointerType *RHSMPType =
6980 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006981 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006982 else
6983 TyRec = ArgExpr->getType()->getAs<RecordType>();
6984 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006985 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006986 VRQuals.addVolatile();
6987 VRQuals.addRestrict();
6988 return VRQuals;
6989 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006990
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006991 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006992 if (!ClassDecl->hasDefinition())
6993 return VRQuals;
6994
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00006995 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00006996 if (isa<UsingShadowDecl>(D))
6997 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6998 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006999 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7000 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7001 CanTy = ResTypeRef->getPointeeType();
7002 // Need to go down the pointer/mempointer chain and add qualifiers
7003 // as see them.
7004 bool done = false;
7005 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007006 if (CanTy.isRestrictQualified())
7007 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007008 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7009 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007010 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007011 CanTy->getAs<MemberPointerType>())
7012 CanTy = ResTypeMPtr->getPointeeType();
7013 else
7014 done = true;
7015 if (CanTy.isVolatileQualified())
7016 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007017 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7018 return VRQuals;
7019 }
7020 }
7021 }
7022 return VRQuals;
7023}
John McCall52872982010-11-13 05:51:15 +00007024
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007025namespace {
John McCall52872982010-11-13 05:51:15 +00007026
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007027/// \brief Helper class to manage the addition of builtin operator overload
7028/// candidates. It provides shared state and utility methods used throughout
7029/// the process, as well as a helper method to add each group of builtin
7030/// operator overloads from the standard to a candidate set.
7031class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007032 // Common instance state available to all overload candidate addition methods.
7033 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007034 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007035 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007036 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007037 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007038 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007039
Chandler Carruthc6586e52010-12-12 10:35:00 +00007040 // Define some constants used to index and iterate over the arithemetic types
7041 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007042 // The "promoted arithmetic types" are the arithmetic
7043 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007044 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007045 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007046 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007047 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007048 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007049 LastPromotedArithmeticType = 11;
7050 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007051
Chandler Carruthc6586e52010-12-12 10:35:00 +00007052 /// \brief Get the canonical type for a given arithmetic type index.
7053 CanQualType getArithmeticType(unsigned index) {
7054 assert(index < NumArithmeticTypes);
7055 static CanQualType ASTContext::* const
7056 ArithmeticTypes[NumArithmeticTypes] = {
7057 // Start of promoted types.
7058 &ASTContext::FloatTy,
7059 &ASTContext::DoubleTy,
7060 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007061
Chandler Carruthc6586e52010-12-12 10:35:00 +00007062 // Start of integral types.
7063 &ASTContext::IntTy,
7064 &ASTContext::LongTy,
7065 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007066 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007067 &ASTContext::UnsignedIntTy,
7068 &ASTContext::UnsignedLongTy,
7069 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007070 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007071 // End of promoted types.
7072
7073 &ASTContext::BoolTy,
7074 &ASTContext::CharTy,
7075 &ASTContext::WCharTy,
7076 &ASTContext::Char16Ty,
7077 &ASTContext::Char32Ty,
7078 &ASTContext::SignedCharTy,
7079 &ASTContext::ShortTy,
7080 &ASTContext::UnsignedCharTy,
7081 &ASTContext::UnsignedShortTy,
7082 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007083 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007084 };
7085 return S.Context.*ArithmeticTypes[index];
7086 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007087
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007088 /// \brief Gets the canonical type resulting from the usual arithemetic
7089 /// converions for the given arithmetic types.
7090 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7091 // Accelerator table for performing the usual arithmetic conversions.
7092 // The rules are basically:
7093 // - if either is floating-point, use the wider floating-point
7094 // - if same signedness, use the higher rank
7095 // - if same size, use unsigned of the higher rank
7096 // - use the larger type
7097 // These rules, together with the axiom that higher ranks are
7098 // never smaller, are sufficient to precompute all of these results
7099 // *except* when dealing with signed types of higher rank.
7100 // (we could precompute SLL x UI for all known platforms, but it's
7101 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007102 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007103 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007104 Dep=-1,
7105 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007106 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007107 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007108 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007109/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7110/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7111/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7112/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7113/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7114/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7115/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7116/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7117/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7118/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7119/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007120 };
7121
7122 assert(L < LastPromotedArithmeticType);
7123 assert(R < LastPromotedArithmeticType);
7124 int Idx = ConversionsTable[L][R];
7125
7126 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007127 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007128
7129 // Slow path: we need to compare widths.
7130 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007131 CanQualType LT = getArithmeticType(L),
7132 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007133 unsigned LW = S.Context.getIntWidth(LT),
7134 RW = S.Context.getIntWidth(RT);
7135
7136 // If they're different widths, use the signed type.
7137 if (LW > RW) return LT;
7138 else if (LW < RW) return RT;
7139
7140 // Otherwise, use the unsigned type of the signed type's rank.
7141 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7142 assert(L == SLL || R == SLL);
7143 return S.Context.UnsignedLongLongTy;
7144 }
7145
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007146 /// \brief Helper method to factor out the common pattern of adding overloads
7147 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007148 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007149 bool HasVolatile,
7150 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007151 QualType ParamTypes[2] = {
7152 S.Context.getLValueReferenceType(CandidateTy),
7153 S.Context.IntTy
7154 };
7155
7156 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007157 if (Args.size() == 1)
7158 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007159 else
Richard Smithe54c3072013-05-05 15:51:06 +00007160 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007161
7162 // Use a heuristic to reduce number of builtin candidates in the set:
7163 // add volatile version only if there are conversions to a volatile type.
7164 if (HasVolatile) {
7165 ParamTypes[0] =
7166 S.Context.getLValueReferenceType(
7167 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007168 if (Args.size() == 1)
7169 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007170 else
Richard Smithe54c3072013-05-05 15:51:06 +00007171 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007172 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007173
7174 // Add restrict version only if there are conversions to a restrict type
7175 // and our candidate type is a non-restrict-qualified pointer.
7176 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7177 !CandidateTy.isRestrictQualified()) {
7178 ParamTypes[0]
7179 = S.Context.getLValueReferenceType(
7180 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007181 if (Args.size() == 1)
7182 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007183 else
Richard Smithe54c3072013-05-05 15:51:06 +00007184 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007185
7186 if (HasVolatile) {
7187 ParamTypes[0]
7188 = S.Context.getLValueReferenceType(
7189 S.Context.getCVRQualifiedType(CandidateTy,
7190 (Qualifiers::Volatile |
7191 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007192 if (Args.size() == 1)
7193 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007194 else
Richard Smithe54c3072013-05-05 15:51:06 +00007195 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007196 }
7197 }
7198
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007199 }
7200
7201public:
7202 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007203 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007204 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007205 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007206 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007207 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007208 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007209 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007210 HasArithmeticOrEnumeralCandidateType(
7211 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007212 CandidateTypes(CandidateTypes),
7213 CandidateSet(CandidateSet) {
7214 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007215 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007216 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007217 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007218 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007219 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007220 assert(getArithmeticType(FirstPromotedArithmeticType)
7221 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007222 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007223 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007224 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007225 "Invalid last promoted arithmetic type");
7226 }
7227
7228 // C++ [over.built]p3:
7229 //
7230 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7231 // is either volatile or empty, there exist candidate operator
7232 // functions of the form
7233 //
7234 // VQ T& operator++(VQ T&);
7235 // T operator++(VQ T&, int);
7236 //
7237 // C++ [over.built]p4:
7238 //
7239 // For every pair (T, VQ), where T is an arithmetic type other
7240 // than bool, and VQ is either volatile or empty, there exist
7241 // candidate operator functions of the form
7242 //
7243 // VQ T& operator--(VQ T&);
7244 // T operator--(VQ T&, int);
7245 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007246 if (!HasArithmeticOrEnumeralCandidateType)
7247 return;
7248
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007249 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7250 Arith < NumArithmeticTypes; ++Arith) {
7251 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007252 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007253 VisibleTypeConversionsQuals.hasVolatile(),
7254 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007255 }
7256 }
7257
7258 // C++ [over.built]p5:
7259 //
7260 // For every pair (T, VQ), where T is a cv-qualified or
7261 // cv-unqualified object type, and VQ is either volatile or
7262 // empty, there exist candidate operator functions of the form
7263 //
7264 // T*VQ& operator++(T*VQ&);
7265 // T*VQ& operator--(T*VQ&);
7266 // T* operator++(T*VQ&, int);
7267 // T* operator--(T*VQ&, int);
7268 void addPlusPlusMinusMinusPointerOverloads() {
7269 for (BuiltinCandidateTypeSet::iterator
7270 Ptr = CandidateTypes[0].pointer_begin(),
7271 PtrEnd = CandidateTypes[0].pointer_end();
7272 Ptr != PtrEnd; ++Ptr) {
7273 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007274 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007275 continue;
7276
7277 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007278 (!(*Ptr).isVolatileQualified() &&
7279 VisibleTypeConversionsQuals.hasVolatile()),
7280 (!(*Ptr).isRestrictQualified() &&
7281 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007282 }
7283 }
7284
7285 // C++ [over.built]p6:
7286 // For every cv-qualified or cv-unqualified object type T, there
7287 // exist candidate operator functions of the form
7288 //
7289 // T& operator*(T*);
7290 //
7291 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007292 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007293 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007294 // T& operator*(T*);
7295 void addUnaryStarPointerOverloads() {
7296 for (BuiltinCandidateTypeSet::iterator
7297 Ptr = CandidateTypes[0].pointer_begin(),
7298 PtrEnd = CandidateTypes[0].pointer_end();
7299 Ptr != PtrEnd; ++Ptr) {
7300 QualType ParamTy = *Ptr;
7301 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007302 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7303 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007304
Douglas Gregor02824322011-01-26 19:30:28 +00007305 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7306 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7307 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007308
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007309 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007310 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007311 }
7312 }
7313
7314 // C++ [over.built]p9:
7315 // For every promoted arithmetic type T, there exist candidate
7316 // operator functions of the form
7317 //
7318 // T operator+(T);
7319 // T operator-(T);
7320 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007321 if (!HasArithmeticOrEnumeralCandidateType)
7322 return;
7323
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007324 for (unsigned Arith = FirstPromotedArithmeticType;
7325 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007326 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007327 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007328 }
7329
7330 // Extension: We also add these operators for vector types.
7331 for (BuiltinCandidateTypeSet::iterator
7332 Vec = CandidateTypes[0].vector_begin(),
7333 VecEnd = CandidateTypes[0].vector_end();
7334 Vec != VecEnd; ++Vec) {
7335 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007336 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007337 }
7338 }
7339
7340 // C++ [over.built]p8:
7341 // For every type T, there exist candidate operator functions of
7342 // the form
7343 //
7344 // T* operator+(T*);
7345 void addUnaryPlusPointerOverloads() {
7346 for (BuiltinCandidateTypeSet::iterator
7347 Ptr = CandidateTypes[0].pointer_begin(),
7348 PtrEnd = CandidateTypes[0].pointer_end();
7349 Ptr != PtrEnd; ++Ptr) {
7350 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007351 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007352 }
7353 }
7354
7355 // C++ [over.built]p10:
7356 // For every promoted integral type T, there exist candidate
7357 // operator functions of the form
7358 //
7359 // T operator~(T);
7360 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007361 if (!HasArithmeticOrEnumeralCandidateType)
7362 return;
7363
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007364 for (unsigned Int = FirstPromotedIntegralType;
7365 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007366 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007367 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007368 }
7369
7370 // Extension: We also add this operator for vector types.
7371 for (BuiltinCandidateTypeSet::iterator
7372 Vec = CandidateTypes[0].vector_begin(),
7373 VecEnd = CandidateTypes[0].vector_end();
7374 Vec != VecEnd; ++Vec) {
7375 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007376 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007377 }
7378 }
7379
7380 // C++ [over.match.oper]p16:
7381 // For every pointer to member type T, there exist candidate operator
7382 // functions of the form
7383 //
7384 // bool operator==(T,T);
7385 // bool operator!=(T,T);
7386 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7387 /// Set of (canonical) types that we've already handled.
7388 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7389
Richard Smithe54c3072013-05-05 15:51:06 +00007390 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007391 for (BuiltinCandidateTypeSet::iterator
7392 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7393 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7394 MemPtr != MemPtrEnd;
7395 ++MemPtr) {
7396 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007397 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007398 continue;
7399
7400 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007401 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007402 }
7403 }
7404 }
7405
7406 // C++ [over.built]p15:
7407 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007408 // For every T, where T is an enumeration type, a pointer type, or
7409 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007410 //
7411 // bool operator<(T, T);
7412 // bool operator>(T, T);
7413 // bool operator<=(T, T);
7414 // bool operator>=(T, T);
7415 // bool operator==(T, T);
7416 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007417 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007418 // C++ [over.match.oper]p3:
7419 // [...]the built-in candidates include all of the candidate operator
7420 // functions defined in 13.6 that, compared to the given operator, [...]
7421 // do not have the same parameter-type-list as any non-template non-member
7422 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007423 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007424 // Note that in practice, this only affects enumeration types because there
7425 // aren't any built-in candidates of record type, and a user-defined operator
7426 // must have an operand of record or enumeration type. Also, the only other
7427 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007428 // cannot be overloaded for enumeration types, so this is the only place
7429 // where we must suppress candidates like this.
7430 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7431 UserDefinedBinaryOperators;
7432
Richard Smithe54c3072013-05-05 15:51:06 +00007433 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007434 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7435 CandidateTypes[ArgIdx].enumeration_end()) {
7436 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7437 CEnd = CandidateSet.end();
7438 C != CEnd; ++C) {
7439 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7440 continue;
7441
Eli Friedman14f082b2012-09-18 21:52:24 +00007442 if (C->Function->isFunctionTemplateSpecialization())
7443 continue;
7444
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007445 QualType FirstParamType =
7446 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7447 QualType SecondParamType =
7448 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7449
7450 // Skip if either parameter isn't of enumeral type.
7451 if (!FirstParamType->isEnumeralType() ||
7452 !SecondParamType->isEnumeralType())
7453 continue;
7454
7455 // Add this operator to the set of known user-defined operators.
7456 UserDefinedBinaryOperators.insert(
7457 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7458 S.Context.getCanonicalType(SecondParamType)));
7459 }
7460 }
7461 }
7462
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007463 /// Set of (canonical) types that we've already handled.
7464 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7465
Richard Smithe54c3072013-05-05 15:51:06 +00007466 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007467 for (BuiltinCandidateTypeSet::iterator
7468 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7469 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7470 Ptr != PtrEnd; ++Ptr) {
7471 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007472 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007473 continue;
7474
7475 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007476 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007477 }
7478 for (BuiltinCandidateTypeSet::iterator
7479 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7480 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7481 Enum != EnumEnd; ++Enum) {
7482 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7483
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007484 // Don't add the same builtin candidate twice, or if a user defined
7485 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007486 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007487 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7488 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007489 continue;
7490
7491 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007492 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007493 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007494
7495 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7496 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007497 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007498 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007499 NullPtrTy))) {
7500 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007501 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007502 CandidateSet);
7503 }
7504 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007505 }
7506 }
7507
7508 // C++ [over.built]p13:
7509 //
7510 // For every cv-qualified or cv-unqualified object type T
7511 // there exist candidate operator functions of the form
7512 //
7513 // T* operator+(T*, ptrdiff_t);
7514 // T& operator[](T*, ptrdiff_t); [BELOW]
7515 // T* operator-(T*, ptrdiff_t);
7516 // T* operator+(ptrdiff_t, T*);
7517 // T& operator[](ptrdiff_t, T*); [BELOW]
7518 //
7519 // C++ [over.built]p14:
7520 //
7521 // For every T, where T is a pointer to object type, there
7522 // exist candidate operator functions of the form
7523 //
7524 // ptrdiff_t operator-(T, T);
7525 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7526 /// Set of (canonical) types that we've already handled.
7527 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7528
7529 for (int Arg = 0; Arg < 2; ++Arg) {
7530 QualType AsymetricParamTypes[2] = {
7531 S.Context.getPointerDiffType(),
7532 S.Context.getPointerDiffType(),
7533 };
7534 for (BuiltinCandidateTypeSet::iterator
7535 Ptr = CandidateTypes[Arg].pointer_begin(),
7536 PtrEnd = CandidateTypes[Arg].pointer_end();
7537 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007538 QualType PointeeTy = (*Ptr)->getPointeeType();
7539 if (!PointeeTy->isObjectType())
7540 continue;
7541
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007542 AsymetricParamTypes[Arg] = *Ptr;
7543 if (Arg == 0 || Op == OO_Plus) {
7544 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7545 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007546 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007547 }
7548 if (Op == OO_Minus) {
7549 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007550 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007551 continue;
7552
7553 QualType ParamTypes[2] = { *Ptr, *Ptr };
7554 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007555 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007556 }
7557 }
7558 }
7559 }
7560
7561 // C++ [over.built]p12:
7562 //
7563 // For every pair of promoted arithmetic types L and R, there
7564 // exist candidate operator functions of the form
7565 //
7566 // LR operator*(L, R);
7567 // LR operator/(L, R);
7568 // LR operator+(L, R);
7569 // LR operator-(L, R);
7570 // bool operator<(L, R);
7571 // bool operator>(L, R);
7572 // bool operator<=(L, R);
7573 // bool operator>=(L, R);
7574 // bool operator==(L, R);
7575 // bool operator!=(L, R);
7576 //
7577 // where LR is the result of the usual arithmetic conversions
7578 // between types L and R.
7579 //
7580 // C++ [over.built]p24:
7581 //
7582 // For every pair of promoted arithmetic types L and R, there exist
7583 // candidate operator functions of the form
7584 //
7585 // LR operator?(bool, L, R);
7586 //
7587 // where LR is the result of the usual arithmetic conversions
7588 // between types L and R.
7589 // Our candidates ignore the first parameter.
7590 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007591 if (!HasArithmeticOrEnumeralCandidateType)
7592 return;
7593
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007594 for (unsigned Left = FirstPromotedArithmeticType;
7595 Left < LastPromotedArithmeticType; ++Left) {
7596 for (unsigned Right = FirstPromotedArithmeticType;
7597 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007598 QualType LandR[2] = { getArithmeticType(Left),
7599 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007600 QualType Result =
7601 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007602 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007603 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007604 }
7605 }
7606
7607 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7608 // conditional operator for vector types.
7609 for (BuiltinCandidateTypeSet::iterator
7610 Vec1 = CandidateTypes[0].vector_begin(),
7611 Vec1End = CandidateTypes[0].vector_end();
7612 Vec1 != Vec1End; ++Vec1) {
7613 for (BuiltinCandidateTypeSet::iterator
7614 Vec2 = CandidateTypes[1].vector_begin(),
7615 Vec2End = CandidateTypes[1].vector_end();
7616 Vec2 != Vec2End; ++Vec2) {
7617 QualType LandR[2] = { *Vec1, *Vec2 };
7618 QualType Result = S.Context.BoolTy;
7619 if (!isComparison) {
7620 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7621 Result = *Vec1;
7622 else
7623 Result = *Vec2;
7624 }
7625
Richard Smithe54c3072013-05-05 15:51:06 +00007626 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007627 }
7628 }
7629 }
7630
7631 // C++ [over.built]p17:
7632 //
7633 // For every pair of promoted integral types L and R, there
7634 // exist candidate operator functions of the form
7635 //
7636 // LR operator%(L, R);
7637 // LR operator&(L, R);
7638 // LR operator^(L, R);
7639 // LR operator|(L, R);
7640 // L operator<<(L, R);
7641 // L operator>>(L, R);
7642 //
7643 // where LR is the result of the usual arithmetic conversions
7644 // between types L and R.
7645 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007646 if (!HasArithmeticOrEnumeralCandidateType)
7647 return;
7648
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007649 for (unsigned Left = FirstPromotedIntegralType;
7650 Left < LastPromotedIntegralType; ++Left) {
7651 for (unsigned Right = FirstPromotedIntegralType;
7652 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007653 QualType LandR[2] = { getArithmeticType(Left),
7654 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007655 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7656 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007657 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007658 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007659 }
7660 }
7661 }
7662
7663 // C++ [over.built]p20:
7664 //
7665 // For every pair (T, VQ), where T is an enumeration or
7666 // pointer to member type and VQ is either volatile or
7667 // empty, there exist candidate operator functions of the form
7668 //
7669 // VQ T& operator=(VQ T&, T);
7670 void addAssignmentMemberPointerOrEnumeralOverloads() {
7671 /// Set of (canonical) types that we've already handled.
7672 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7673
7674 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7675 for (BuiltinCandidateTypeSet::iterator
7676 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7677 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7678 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007679 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007680 continue;
7681
Richard Smithe54c3072013-05-05 15:51:06 +00007682 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007683 }
7684
7685 for (BuiltinCandidateTypeSet::iterator
7686 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7687 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7688 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007689 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007690 continue;
7691
Richard Smithe54c3072013-05-05 15:51:06 +00007692 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007693 }
7694 }
7695 }
7696
7697 // C++ [over.built]p19:
7698 //
7699 // For every pair (T, VQ), where T is any type and VQ is either
7700 // volatile or empty, there exist candidate operator functions
7701 // of the form
7702 //
7703 // T*VQ& operator=(T*VQ&, T*);
7704 //
7705 // C++ [over.built]p21:
7706 //
7707 // For every pair (T, VQ), where T is a cv-qualified or
7708 // cv-unqualified object type and VQ is either volatile or
7709 // empty, there exist candidate operator functions of the form
7710 //
7711 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7712 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7713 void addAssignmentPointerOverloads(bool isEqualOp) {
7714 /// Set of (canonical) types that we've already handled.
7715 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7716
7717 for (BuiltinCandidateTypeSet::iterator
7718 Ptr = CandidateTypes[0].pointer_begin(),
7719 PtrEnd = CandidateTypes[0].pointer_end();
7720 Ptr != PtrEnd; ++Ptr) {
7721 // If this is operator=, keep track of the builtin candidates we added.
7722 if (isEqualOp)
7723 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007724 else if (!(*Ptr)->getPointeeType()->isObjectType())
7725 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007726
7727 // non-volatile version
7728 QualType ParamTypes[2] = {
7729 S.Context.getLValueReferenceType(*Ptr),
7730 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7731 };
Richard Smithe54c3072013-05-05 15:51:06 +00007732 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007733 /*IsAssigmentOperator=*/ isEqualOp);
7734
Douglas Gregor5bee2582012-06-04 00:15:09 +00007735 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7736 VisibleTypeConversionsQuals.hasVolatile();
7737 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007738 // volatile version
7739 ParamTypes[0] =
7740 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007741 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007742 /*IsAssigmentOperator=*/isEqualOp);
7743 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007744
7745 if (!(*Ptr).isRestrictQualified() &&
7746 VisibleTypeConversionsQuals.hasRestrict()) {
7747 // restrict version
7748 ParamTypes[0]
7749 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007750 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007751 /*IsAssigmentOperator=*/isEqualOp);
7752
7753 if (NeedVolatile) {
7754 // volatile restrict version
7755 ParamTypes[0]
7756 = S.Context.getLValueReferenceType(
7757 S.Context.getCVRQualifiedType(*Ptr,
7758 (Qualifiers::Volatile |
7759 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007760 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007761 /*IsAssigmentOperator=*/isEqualOp);
7762 }
7763 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007764 }
7765
7766 if (isEqualOp) {
7767 for (BuiltinCandidateTypeSet::iterator
7768 Ptr = CandidateTypes[1].pointer_begin(),
7769 PtrEnd = CandidateTypes[1].pointer_end();
7770 Ptr != PtrEnd; ++Ptr) {
7771 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007772 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007773 continue;
7774
Chandler Carruth8e543b32010-12-12 08:17:55 +00007775 QualType ParamTypes[2] = {
7776 S.Context.getLValueReferenceType(*Ptr),
7777 *Ptr,
7778 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007779
7780 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007781 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007782 /*IsAssigmentOperator=*/true);
7783
Douglas Gregor5bee2582012-06-04 00:15:09 +00007784 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7785 VisibleTypeConversionsQuals.hasVolatile();
7786 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007787 // volatile version
7788 ParamTypes[0] =
7789 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007790 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7791 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007792 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007793
7794 if (!(*Ptr).isRestrictQualified() &&
7795 VisibleTypeConversionsQuals.hasRestrict()) {
7796 // restrict version
7797 ParamTypes[0]
7798 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007799 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7800 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007801
7802 if (NeedVolatile) {
7803 // volatile restrict version
7804 ParamTypes[0]
7805 = S.Context.getLValueReferenceType(
7806 S.Context.getCVRQualifiedType(*Ptr,
7807 (Qualifiers::Volatile |
7808 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007809 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7810 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007811 }
7812 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007813 }
7814 }
7815 }
7816
7817 // C++ [over.built]p18:
7818 //
7819 // For every triple (L, VQ, R), where L is an arithmetic type,
7820 // VQ is either volatile or empty, and R is a promoted
7821 // arithmetic type, there exist candidate operator functions of
7822 // the form
7823 //
7824 // VQ L& operator=(VQ L&, R);
7825 // VQ L& operator*=(VQ L&, R);
7826 // VQ L& operator/=(VQ L&, R);
7827 // VQ L& operator+=(VQ L&, R);
7828 // VQ L& operator-=(VQ L&, R);
7829 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007830 if (!HasArithmeticOrEnumeralCandidateType)
7831 return;
7832
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007833 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7834 for (unsigned Right = FirstPromotedArithmeticType;
7835 Right < LastPromotedArithmeticType; ++Right) {
7836 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007837 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007838
7839 // Add this built-in operator as a candidate (VQ is empty).
7840 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007841 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007842 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007843 /*IsAssigmentOperator=*/isEqualOp);
7844
7845 // Add this built-in operator as a candidate (VQ is 'volatile').
7846 if (VisibleTypeConversionsQuals.hasVolatile()) {
7847 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007848 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007849 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007850 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007851 /*IsAssigmentOperator=*/isEqualOp);
7852 }
7853 }
7854 }
7855
7856 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7857 for (BuiltinCandidateTypeSet::iterator
7858 Vec1 = CandidateTypes[0].vector_begin(),
7859 Vec1End = CandidateTypes[0].vector_end();
7860 Vec1 != Vec1End; ++Vec1) {
7861 for (BuiltinCandidateTypeSet::iterator
7862 Vec2 = CandidateTypes[1].vector_begin(),
7863 Vec2End = CandidateTypes[1].vector_end();
7864 Vec2 != Vec2End; ++Vec2) {
7865 QualType ParamTypes[2];
7866 ParamTypes[1] = *Vec2;
7867 // Add this built-in operator as a candidate (VQ is empty).
7868 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007869 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007870 /*IsAssigmentOperator=*/isEqualOp);
7871
7872 // Add this built-in operator as a candidate (VQ is 'volatile').
7873 if (VisibleTypeConversionsQuals.hasVolatile()) {
7874 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7875 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007876 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007877 /*IsAssigmentOperator=*/isEqualOp);
7878 }
7879 }
7880 }
7881 }
7882
7883 // C++ [over.built]p22:
7884 //
7885 // For every triple (L, VQ, R), where L is an integral type, VQ
7886 // is either volatile or empty, and R is a promoted integral
7887 // type, there exist candidate operator functions of the form
7888 //
7889 // VQ L& operator%=(VQ L&, R);
7890 // VQ L& operator<<=(VQ L&, R);
7891 // VQ L& operator>>=(VQ L&, R);
7892 // VQ L& operator&=(VQ L&, R);
7893 // VQ L& operator^=(VQ L&, R);
7894 // VQ L& operator|=(VQ L&, R);
7895 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007896 if (!HasArithmeticOrEnumeralCandidateType)
7897 return;
7898
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007899 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7900 for (unsigned Right = FirstPromotedIntegralType;
7901 Right < LastPromotedIntegralType; ++Right) {
7902 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007903 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007904
7905 // Add this built-in operator as a candidate (VQ is empty).
7906 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007907 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007908 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007909 if (VisibleTypeConversionsQuals.hasVolatile()) {
7910 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007911 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007912 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7913 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007914 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007915 }
7916 }
7917 }
7918 }
7919
7920 // C++ [over.operator]p23:
7921 //
7922 // There also exist candidate operator functions of the form
7923 //
7924 // bool operator!(bool);
7925 // bool operator&&(bool, bool);
7926 // bool operator||(bool, bool);
7927 void addExclaimOverload() {
7928 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007929 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007930 /*IsAssignmentOperator=*/false,
7931 /*NumContextualBoolArguments=*/1);
7932 }
7933 void addAmpAmpOrPipePipeOverload() {
7934 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007935 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007936 /*IsAssignmentOperator=*/false,
7937 /*NumContextualBoolArguments=*/2);
7938 }
7939
7940 // C++ [over.built]p13:
7941 //
7942 // For every cv-qualified or cv-unqualified object type T there
7943 // exist candidate operator functions of the form
7944 //
7945 // T* operator+(T*, ptrdiff_t); [ABOVE]
7946 // T& operator[](T*, ptrdiff_t);
7947 // T* operator-(T*, ptrdiff_t); [ABOVE]
7948 // T* operator+(ptrdiff_t, T*); [ABOVE]
7949 // T& operator[](ptrdiff_t, T*);
7950 void addSubscriptOverloads() {
7951 for (BuiltinCandidateTypeSet::iterator
7952 Ptr = CandidateTypes[0].pointer_begin(),
7953 PtrEnd = CandidateTypes[0].pointer_end();
7954 Ptr != PtrEnd; ++Ptr) {
7955 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7956 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007957 if (!PointeeType->isObjectType())
7958 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007959
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007960 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7961
7962 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007963 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007964 }
7965
7966 for (BuiltinCandidateTypeSet::iterator
7967 Ptr = CandidateTypes[1].pointer_begin(),
7968 PtrEnd = CandidateTypes[1].pointer_end();
7969 Ptr != PtrEnd; ++Ptr) {
7970 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7971 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007972 if (!PointeeType->isObjectType())
7973 continue;
7974
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007975 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7976
7977 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00007978 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007979 }
7980 }
7981
7982 // C++ [over.built]p11:
7983 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7984 // C1 is the same type as C2 or is a derived class of C2, T is an object
7985 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7986 // there exist candidate operator functions of the form
7987 //
7988 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7989 //
7990 // where CV12 is the union of CV1 and CV2.
7991 void addArrowStarOverloads() {
7992 for (BuiltinCandidateTypeSet::iterator
7993 Ptr = CandidateTypes[0].pointer_begin(),
7994 PtrEnd = CandidateTypes[0].pointer_end();
7995 Ptr != PtrEnd; ++Ptr) {
7996 QualType C1Ty = (*Ptr);
7997 QualType C1;
7998 QualifierCollector Q1;
7999 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8000 if (!isa<RecordType>(C1))
8001 continue;
8002 // heuristic to reduce number of builtin candidates in the set.
8003 // Add volatile/restrict version only if there are conversions to a
8004 // volatile/restrict type.
8005 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8006 continue;
8007 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8008 continue;
8009 for (BuiltinCandidateTypeSet::iterator
8010 MemPtr = CandidateTypes[1].member_pointer_begin(),
8011 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8012 MemPtr != MemPtrEnd; ++MemPtr) {
8013 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8014 QualType C2 = QualType(mptr->getClass(), 0);
8015 C2 = C2.getUnqualifiedType();
8016 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8017 break;
8018 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8019 // build CV12 T&
8020 QualType T = mptr->getPointeeType();
8021 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8022 T.isVolatileQualified())
8023 continue;
8024 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8025 T.isRestrictQualified())
8026 continue;
8027 T = Q1.apply(S.Context, T);
8028 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008029 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008030 }
8031 }
8032 }
8033
8034 // Note that we don't consider the first argument, since it has been
8035 // contextually converted to bool long ago. The candidates below are
8036 // therefore added as binary.
8037 //
8038 // C++ [over.built]p25:
8039 // For every type T, where T is a pointer, pointer-to-member, or scoped
8040 // enumeration type, there exist candidate operator functions of the form
8041 //
8042 // T operator?(bool, T, T);
8043 //
8044 void addConditionalOperatorOverloads() {
8045 /// Set of (canonical) types that we've already handled.
8046 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8047
8048 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8049 for (BuiltinCandidateTypeSet::iterator
8050 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8051 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8052 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008053 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008054 continue;
8055
8056 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008057 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008058 }
8059
8060 for (BuiltinCandidateTypeSet::iterator
8061 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8062 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8063 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008064 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008065 continue;
8066
8067 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008068 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008069 }
8070
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008071 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008072 for (BuiltinCandidateTypeSet::iterator
8073 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8074 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8075 Enum != EnumEnd; ++Enum) {
8076 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8077 continue;
8078
David Blaikie82e95a32014-11-19 07:49:47 +00008079 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008080 continue;
8081
8082 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008083 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008084 }
8085 }
8086 }
8087 }
8088};
8089
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008090} // end anonymous namespace
8091
8092/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8093/// operator overloads to the candidate set (C++ [over.built]), based
8094/// on the operator @p Op and the arguments given. For example, if the
8095/// operator is a binary '+', this routine might add "int
8096/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008097void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8098 SourceLocation OpLoc,
8099 ArrayRef<Expr *> Args,
8100 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008101 // Find all of the types that the arguments can convert to, but only
8102 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008103 // that make use of these types. Also record whether we encounter non-record
8104 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008105 Qualifiers VisibleTypeConversionsQuals;
8106 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008107 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008108 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008109
8110 bool HasNonRecordCandidateType = false;
8111 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008112 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008113 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008114 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008115 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8116 OpLoc,
8117 true,
8118 (Op == OO_Exclaim ||
8119 Op == OO_AmpAmp ||
8120 Op == OO_PipePipe),
8121 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008122 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8123 CandidateTypes[ArgIdx].hasNonRecordTypes();
8124 HasArithmeticOrEnumeralCandidateType =
8125 HasArithmeticOrEnumeralCandidateType ||
8126 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008127 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008128
Chandler Carruth00a38332010-12-13 01:44:01 +00008129 // Exit early when no non-record types have been added to the candidate set
8130 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008131 //
8132 // We can't exit early for !, ||, or &&, since there we have always have
8133 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008134 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008135 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008136 return;
8137
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008138 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008139 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008140 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008141 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008142 CandidateTypes, CandidateSet);
8143
8144 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008145 switch (Op) {
8146 case OO_None:
8147 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008148 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008149
Chandler Carruth5184de02010-12-12 08:51:33 +00008150 case OO_New:
8151 case OO_Delete:
8152 case OO_Array_New:
8153 case OO_Array_Delete:
8154 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008155 llvm_unreachable(
8156 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008157
8158 case OO_Comma:
8159 case OO_Arrow:
8160 // C++ [over.match.oper]p3:
8161 // -- For the operator ',', the unary operator '&', or the
8162 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008163 break;
8164
8165 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008166 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008167 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008168 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008169
8170 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008171 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008172 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008173 } else {
8174 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8175 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8176 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008177 break;
8178
Chandler Carruth5184de02010-12-12 08:51:33 +00008179 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008180 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008181 OpBuilder.addUnaryStarPointerOverloads();
8182 else
8183 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8184 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008185
Chandler Carruth5184de02010-12-12 08:51:33 +00008186 case OO_Slash:
8187 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008188 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008189
8190 case OO_PlusPlus:
8191 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008192 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8193 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008194 break;
8195
Douglas Gregor84605ae2009-08-24 13:43:27 +00008196 case OO_EqualEqual:
8197 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008198 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008199 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008200
Douglas Gregora11693b2008-11-12 17:17:38 +00008201 case OO_Less:
8202 case OO_Greater:
8203 case OO_LessEqual:
8204 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008205 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008206 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8207 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008208
Douglas Gregora11693b2008-11-12 17:17:38 +00008209 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008210 case OO_Caret:
8211 case OO_Pipe:
8212 case OO_LessLess:
8213 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008214 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008215 break;
8216
Chandler Carruth5184de02010-12-12 08:51:33 +00008217 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008218 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008219 // C++ [over.match.oper]p3:
8220 // -- For the operator ',', the unary operator '&', or the
8221 // operator '->', the built-in candidates set is empty.
8222 break;
8223
8224 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8225 break;
8226
8227 case OO_Tilde:
8228 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8229 break;
8230
Douglas Gregora11693b2008-11-12 17:17:38 +00008231 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008232 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008233 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008234
8235 case OO_PlusEqual:
8236 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008237 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008238 // Fall through.
8239
8240 case OO_StarEqual:
8241 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008242 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008243 break;
8244
8245 case OO_PercentEqual:
8246 case OO_LessLessEqual:
8247 case OO_GreaterGreaterEqual:
8248 case OO_AmpEqual:
8249 case OO_CaretEqual:
8250 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008251 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008252 break;
8253
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008254 case OO_Exclaim:
8255 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008256 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008257
Douglas Gregora11693b2008-11-12 17:17:38 +00008258 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008259 case OO_PipePipe:
8260 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008261 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008262
8263 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008264 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008265 break;
8266
8267 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008268 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008269 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008270
8271 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008272 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008273 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8274 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008275 }
8276}
8277
Douglas Gregore254f902009-02-04 00:32:51 +00008278/// \brief Add function candidates found via argument-dependent lookup
8279/// to the set of overloading candidates.
8280///
8281/// This routine performs argument-dependent name lookup based on the
8282/// given function name (which may also be an operator name) and adds
8283/// all of the overload candidates found by ADL to the overload
8284/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008285void
Douglas Gregore254f902009-02-04 00:32:51 +00008286Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008287 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008288 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008289 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008290 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008291 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008292 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008293
John McCall91f61fc2010-01-26 06:04:06 +00008294 // FIXME: This approach for uniquing ADL results (and removing
8295 // redundant candidates from the set) relies on pointer-equality,
8296 // which means we need to key off the canonical decl. However,
8297 // always going back to the canonical decl might not get us the
8298 // right set of default arguments. What default arguments are
8299 // we supposed to consider on ADL candidates, anyway?
8300
Douglas Gregorcabea402009-09-22 15:41:20 +00008301 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008302 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008303
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008304 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008305 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8306 CandEnd = CandidateSet.end();
8307 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008308 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008309 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008310 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008311 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008312 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008313
8314 // For each of the ADL candidates we found, add it to the overload
8315 // set.
John McCall8fe68082010-01-26 07:16:45 +00008316 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008317 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008318 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008319 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008320 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008321
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008322 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8323 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008324 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008325 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008326 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008327 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008328 }
Douglas Gregore254f902009-02-04 00:32:51 +00008329}
8330
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008331/// isBetterOverloadCandidate - Determines whether the first overload
8332/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008333bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8334 const OverloadCandidate &Cand2,
8335 SourceLocation Loc,
8336 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008337 // Define viable functions to be better candidates than non-viable
8338 // functions.
8339 if (!Cand2.Viable)
8340 return Cand1.Viable;
8341 else if (!Cand1.Viable)
8342 return false;
8343
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008344 // C++ [over.match.best]p1:
8345 //
8346 // -- if F is a static member function, ICS1(F) is defined such
8347 // that ICS1(F) is neither better nor worse than ICS1(G) for
8348 // any function G, and, symmetrically, ICS1(G) is neither
8349 // better nor worse than ICS1(F).
8350 unsigned StartArg = 0;
8351 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8352 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008353
Douglas Gregord3cb3562009-07-07 23:38:56 +00008354 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008355 // A viable function F1 is defined to be a better function than another
8356 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008357 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008358 unsigned NumArgs = Cand1.NumConversions;
8359 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008360 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008361 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008362 switch (CompareImplicitConversionSequences(S,
8363 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008364 Cand2.Conversions[ArgIdx])) {
8365 case ImplicitConversionSequence::Better:
8366 // Cand1 has a better conversion sequence.
8367 HasBetterConversion = true;
8368 break;
8369
8370 case ImplicitConversionSequence::Worse:
8371 // Cand1 can't be better than Cand2.
8372 return false;
8373
8374 case ImplicitConversionSequence::Indistinguishable:
8375 // Do nothing.
8376 break;
8377 }
8378 }
8379
Mike Stump11289f42009-09-09 15:08:12 +00008380 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008381 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008382 if (HasBetterConversion)
8383 return true;
8384
Douglas Gregora1f013e2008-11-07 22:36:19 +00008385 // -- the context is an initialization by user-defined conversion
8386 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8387 // from the return type of F1 to the destination type (i.e.,
8388 // the type of the entity being initialized) is a better
8389 // conversion sequence than the standard conversion sequence
8390 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008391 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008392 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008393 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008394 // First check whether we prefer one of the conversion functions over the
8395 // other. This only distinguishes the results in non-standard, extension
8396 // cases such as the conversion from a lambda closure type to a function
8397 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008398 ImplicitConversionSequence::CompareKind Result =
8399 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8400 if (Result == ImplicitConversionSequence::Indistinguishable)
8401 Result = CompareStandardConversionSequences(S,
8402 Cand1.FinalConversion,
8403 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008404
Richard Smithec2748a2014-05-17 04:36:39 +00008405 if (Result != ImplicitConversionSequence::Indistinguishable)
8406 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008407
8408 // FIXME: Compare kind of reference binding if conversion functions
8409 // convert to a reference type used in direct reference binding, per
8410 // C++14 [over.match.best]p1 section 2 bullet 3.
8411 }
8412
8413 // -- F1 is a non-template function and F2 is a function template
8414 // specialization, or, if not that,
8415 bool Cand1IsSpecialization = Cand1.Function &&
8416 Cand1.Function->getPrimaryTemplate();
8417 bool Cand2IsSpecialization = Cand2.Function &&
8418 Cand2.Function->getPrimaryTemplate();
8419 if (Cand1IsSpecialization != Cand2IsSpecialization)
8420 return Cand2IsSpecialization;
8421
8422 // -- F1 and F2 are function template specializations, and the function
8423 // template for F1 is more specialized than the template for F2
8424 // according to the partial ordering rules described in 14.5.5.2, or,
8425 // if not that,
8426 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8427 if (FunctionTemplateDecl *BetterTemplate
8428 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8429 Cand2.Function->getPrimaryTemplate(),
8430 Loc,
8431 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8432 : TPOC_Call,
8433 Cand1.ExplicitCallArguments,
8434 Cand2.ExplicitCallArguments))
8435 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008436 }
8437
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008438 // Check for enable_if value-based overload resolution.
8439 if (Cand1.Function && Cand2.Function &&
8440 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8441 Cand2.Function->hasAttr<EnableIfAttr>())) {
8442 // FIXME: The next several lines are just
8443 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8444 // instead of reverse order which is how they're stored in the AST.
8445 AttrVec Cand1Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008446 if (Cand1.Function->hasAttrs()) {
8447 Cand1Attrs = Cand1.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008448 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8449 IsNotEnableIfAttr),
8450 Cand1Attrs.end());
8451 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008452 }
8453
8454 AttrVec Cand2Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008455 if (Cand2.Function->hasAttrs()) {
8456 Cand2Attrs = Cand2.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008457 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8458 IsNotEnableIfAttr),
8459 Cand2Attrs.end());
8460 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008461 }
Richard Smith9516eee2014-05-17 02:21:47 +00008462
8463 // Candidate 1 is better if it has strictly more attributes and
8464 // the common sequence is identical.
8465 if (Cand1Attrs.size() <= Cand2Attrs.size())
8466 return false;
8467
8468 auto Cand1I = Cand1Attrs.begin();
8469 for (auto &Cand2A : Cand2Attrs) {
8470 auto &Cand1A = *Cand1I++;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008471 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Richard Smith9516eee2014-05-17 02:21:47 +00008472 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8473 S.getASTContext(), true);
8474 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8475 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008476 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008477 return false;
8478 }
Richard Smith9516eee2014-05-17 02:21:47 +00008479
8480 return true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008481 }
8482
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008483 return false;
8484}
8485
Mike Stump11289f42009-09-09 15:08:12 +00008486/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008487/// within an overload candidate set.
8488///
James Dennettffad8b72012-06-22 08:10:18 +00008489/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008490/// which overload resolution occurs.
8491///
James Dennettffad8b72012-06-22 08:10:18 +00008492/// \param Best If overload resolution was successful or found a deleted
8493/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008494///
8495/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008496OverloadingResult
8497OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008498 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008499 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008500 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008501 Best = end();
8502 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8503 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008504 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008505 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008506 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008507 }
8508
8509 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008510 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008511 return OR_No_Viable_Function;
8512
8513 // Make sure that this function is better than every other viable
8514 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008515 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008516 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008517 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008518 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008519 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008520 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008521 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008522 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008523 }
Mike Stump11289f42009-09-09 15:08:12 +00008524
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008525 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008526 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008527 (Best->Function->isDeleted() ||
8528 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008529 return OR_Deleted;
8530
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008531 return OR_Success;
8532}
8533
John McCall53262c92010-01-12 02:15:36 +00008534namespace {
8535
8536enum OverloadCandidateKind {
8537 oc_function,
8538 oc_method,
8539 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008540 oc_function_template,
8541 oc_method_template,
8542 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008543 oc_implicit_default_constructor,
8544 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008545 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008546 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008547 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008548 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008549};
8550
John McCalle1ac8d12010-01-13 00:25:19 +00008551OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8552 FunctionDecl *Fn,
8553 std::string &Description) {
8554 bool isTemplate = false;
8555
8556 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8557 isTemplate = true;
8558 Description = S.getTemplateArgumentBindingsText(
8559 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8560 }
John McCallfd0b2f82010-01-06 09:43:14 +00008561
8562 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008563 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008564 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008565
Sebastian Redl08905022011-02-05 19:23:19 +00008566 if (Ctor->getInheritedConstructor())
8567 return oc_implicit_inherited_constructor;
8568
Alexis Hunt119c10e2011-05-25 23:16:36 +00008569 if (Ctor->isDefaultConstructor())
8570 return oc_implicit_default_constructor;
8571
8572 if (Ctor->isMoveConstructor())
8573 return oc_implicit_move_constructor;
8574
8575 assert(Ctor->isCopyConstructor() &&
8576 "unexpected sort of implicit constructor");
8577 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008578 }
8579
8580 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8581 // This actually gets spelled 'candidate function' for now, but
8582 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008583 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008584 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008585
Alexis Hunt119c10e2011-05-25 23:16:36 +00008586 if (Meth->isMoveAssignmentOperator())
8587 return oc_implicit_move_assignment;
8588
Douglas Gregor12695102012-02-10 08:36:38 +00008589 if (Meth->isCopyAssignmentOperator())
8590 return oc_implicit_copy_assignment;
8591
8592 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8593 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008594 }
8595
John McCalle1ac8d12010-01-13 00:25:19 +00008596 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008597}
8598
Larisse Voufo98b20f12013-07-19 23:00:19 +00008599void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008600 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8601 if (!Ctor) return;
8602
8603 Ctor = Ctor->getInheritedConstructor();
8604 if (!Ctor) return;
8605
8606 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8607}
8608
John McCall53262c92010-01-12 02:15:36 +00008609} // end anonymous namespace
8610
8611// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008612void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008613 std::string FnDesc;
8614 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008615 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8616 << (unsigned) K << FnDesc;
8617 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8618 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008619 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008620}
8621
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008622// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008623// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008624void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008625 assert(OverloadedExpr->getType() == Context.OverloadTy);
8626
8627 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8628 OverloadExpr *OvlExpr = Ovl.Expression;
8629
8630 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8631 IEnd = OvlExpr->decls_end();
8632 I != IEnd; ++I) {
8633 if (FunctionTemplateDecl *FunTmpl =
8634 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008635 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008636 } else if (FunctionDecl *Fun
8637 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008638 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008639 }
8640 }
8641}
8642
John McCall0d1da222010-01-12 00:44:57 +00008643/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8644/// "lead" diagnostic; it will be given two arguments, the source and
8645/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008646void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8647 Sema &S,
8648 SourceLocation CaretLoc,
8649 const PartialDiagnostic &PDiag) const {
8650 S.Diag(CaretLoc, PDiag)
8651 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008652 // FIXME: The note limiting machinery is borrowed from
8653 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8654 // refactoring here.
8655 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8656 unsigned CandsShown = 0;
8657 AmbiguousConversionSequence::const_iterator I, E;
8658 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8659 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8660 break;
8661 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008662 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008663 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008664 if (I != E)
8665 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008666}
8667
Richard Smith17c00b42014-11-12 01:24:00 +00008668static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8669 unsigned I) {
John McCall6a61b522010-01-13 09:16:55 +00008670 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8671 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008672 assert(Cand->Function && "for now, candidate must be a function");
8673 FunctionDecl *Fn = Cand->Function;
8674
8675 // There's a conversion slot for the object argument if this is a
8676 // non-constructor method. Note that 'I' corresponds the
8677 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008678 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008679 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008680 if (I == 0)
8681 isObjectArgument = true;
8682 else
8683 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008684 }
8685
John McCalle1ac8d12010-01-13 00:25:19 +00008686 std::string FnDesc;
8687 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8688
John McCall6a61b522010-01-13 09:16:55 +00008689 Expr *FromExpr = Conv.Bad.FromExpr;
8690 QualType FromTy = Conv.Bad.getFromType();
8691 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008692
John McCallfb7ad0f2010-02-02 02:42:52 +00008693 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008694 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008695 Expr *E = FromExpr->IgnoreParens();
8696 if (isa<UnaryOperator>(E))
8697 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008698 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008699
8700 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8701 << (unsigned) FnKind << FnDesc
8702 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8703 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008704 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008705 return;
8706 }
8707
John McCall6d174642010-01-23 08:10:49 +00008708 // Do some hand-waving analysis to see if the non-viability is due
8709 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008710 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8711 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8712 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8713 CToTy = RT->getPointeeType();
8714 else {
8715 // TODO: detect and diagnose the full richness of const mismatches.
8716 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8717 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8718 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8719 }
8720
8721 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8722 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008723 Qualifiers FromQs = CFromTy.getQualifiers();
8724 Qualifiers ToQs = CToTy.getQualifiers();
8725
8726 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8727 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8728 << (unsigned) FnKind << FnDesc
8729 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8730 << FromTy
8731 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8732 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008733 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008734 return;
8735 }
8736
John McCall31168b02011-06-15 23:02:42 +00008737 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008738 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008739 << (unsigned) FnKind << FnDesc
8740 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8741 << FromTy
8742 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8743 << (unsigned) isObjectArgument << I+1;
8744 MaybeEmitInheritedConstructorNote(S, Fn);
8745 return;
8746 }
8747
Douglas Gregoraec25842011-04-26 23:16:46 +00008748 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8749 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8750 << (unsigned) FnKind << FnDesc
8751 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8752 << FromTy
8753 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8754 << (unsigned) isObjectArgument << I+1;
8755 MaybeEmitInheritedConstructorNote(S, Fn);
8756 return;
8757 }
8758
John McCall47000992010-01-14 03:28:57 +00008759 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8760 assert(CVR && "unexpected qualifiers mismatch");
8761
8762 if (isObjectArgument) {
8763 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8764 << (unsigned) FnKind << FnDesc
8765 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8766 << FromTy << (CVR - 1);
8767 } else {
8768 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8769 << (unsigned) FnKind << FnDesc
8770 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8771 << FromTy << (CVR - 1) << I+1;
8772 }
Sebastian Redl08905022011-02-05 19:23:19 +00008773 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008774 return;
8775 }
8776
Sebastian Redla72462c2011-09-24 17:48:32 +00008777 // Special diagnostic for failure to convert an initializer list, since
8778 // telling the user that it has type void is not useful.
8779 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8780 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8781 << (unsigned) FnKind << FnDesc
8782 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8783 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8784 MaybeEmitInheritedConstructorNote(S, Fn);
8785 return;
8786 }
8787
John McCall6d174642010-01-23 08:10:49 +00008788 // Diagnose references or pointers to incomplete types differently,
8789 // since it's far from impossible that the incompleteness triggered
8790 // the failure.
8791 QualType TempFromTy = FromTy.getNonReferenceType();
8792 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8793 TempFromTy = PTy->getPointeeType();
8794 if (TempFromTy->isIncompleteType()) {
8795 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8796 << (unsigned) FnKind << FnDesc
8797 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8798 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008799 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008800 return;
8801 }
8802
Douglas Gregor56f2e342010-06-30 23:01:39 +00008803 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008804 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008805 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8806 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8807 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8808 FromPtrTy->getPointeeType()) &&
8809 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8810 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008811 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008812 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008813 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008814 }
8815 } else if (const ObjCObjectPointerType *FromPtrTy
8816 = FromTy->getAs<ObjCObjectPointerType>()) {
8817 if (const ObjCObjectPointerType *ToPtrTy
8818 = ToTy->getAs<ObjCObjectPointerType>())
8819 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8820 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8821 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8822 FromPtrTy->getPointeeType()) &&
8823 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008824 BaseToDerivedConversion = 2;
8825 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008826 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8827 !FromTy->isIncompleteType() &&
8828 !ToRefTy->getPointeeType()->isIncompleteType() &&
8829 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8830 BaseToDerivedConversion = 3;
8831 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8832 ToTy.getNonReferenceType().getCanonicalType() ==
8833 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008834 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8835 << (unsigned) FnKind << FnDesc
8836 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8837 << (unsigned) isObjectArgument << I + 1;
8838 MaybeEmitInheritedConstructorNote(S, Fn);
8839 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008840 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008842
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008843 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008844 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008845 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008846 << (unsigned) FnKind << FnDesc
8847 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008848 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008849 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008850 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008851 return;
8852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008853
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008854 if (isa<ObjCObjectPointerType>(CFromTy) &&
8855 isa<PointerType>(CToTy)) {
8856 Qualifiers FromQs = CFromTy.getQualifiers();
8857 Qualifiers ToQs = CToTy.getQualifiers();
8858 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8859 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8860 << (unsigned) FnKind << FnDesc
8861 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8862 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8863 MaybeEmitInheritedConstructorNote(S, Fn);
8864 return;
8865 }
8866 }
8867
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008868 // Emit the generic diagnostic and, optionally, add the hints to it.
8869 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8870 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008871 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008872 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8873 << (unsigned) (Cand->Fix.Kind);
8874
8875 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008876 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8877 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008878 FDiag << *HI;
8879 S.Diag(Fn->getLocation(), FDiag);
8880
Sebastian Redl08905022011-02-05 19:23:19 +00008881 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008882}
8883
Larisse Voufo98b20f12013-07-19 23:00:19 +00008884/// Additional arity mismatch diagnosis specific to a function overload
8885/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8886/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008887static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8888 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008889 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008890 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008891
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008892 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008893 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008894 // right number of arguments, because only overloaded operators have
8895 // the weird behavior of overloading member and non-member functions.
8896 // Just don't report anything.
8897 if (Fn->isInvalidDecl() &&
8898 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008899 return true;
8900
8901 if (NumArgs < MinParams) {
8902 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8903 (Cand->FailureKind == ovl_fail_bad_deduction &&
8904 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8905 } else {
8906 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8907 (Cand->FailureKind == ovl_fail_bad_deduction &&
8908 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8909 }
8910
8911 return false;
8912}
8913
8914/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008915static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008916 assert(isa<FunctionDecl>(D) &&
8917 "The templated declaration should at least be a function"
8918 " when diagnosing bad template argument deduction due to too many"
8919 " or too few arguments");
8920
8921 FunctionDecl *Fn = cast<FunctionDecl>(D);
8922
8923 // TODO: treat calls to a missing default constructor as a special case
8924 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8925 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008926
John McCall6a61b522010-01-13 09:16:55 +00008927 // at least / at most / exactly
8928 unsigned mode, modeCount;
8929 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008930 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8931 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008932 mode = 0; // "at least"
8933 else
8934 mode = 2; // "exactly"
8935 modeCount = MinParams;
8936 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008937 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008938 mode = 1; // "at most"
8939 else
8940 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008941 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008942 }
8943
8944 std::string Description;
8945 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8946
Richard Smith10ff50d2012-05-11 05:16:41 +00008947 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8948 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00008949 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8950 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00008951 else
8952 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00008953 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8954 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008955 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008956}
8957
Larisse Voufo98b20f12013-07-19 23:00:19 +00008958/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00008959static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8960 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008961 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8962 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8963}
Larisse Voufo47c08452013-07-19 22:53:23 +00008964
Richard Smith17c00b42014-11-12 01:24:00 +00008965static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008966 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8967 return FD->getDescribedFunctionTemplate();
8968 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8969 return RD->getDescribedClassTemplate();
8970
8971 llvm_unreachable("Unsupported: Getting the described template declaration"
8972 " for bad deduction diagnosis");
8973}
8974
8975/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00008976static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8977 DeductionFailureInfo &DeductionFailure,
8978 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008979 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008980 NamedDecl *ParamD;
8981 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8982 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8983 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00008984 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00008985 case Sema::TDK_Success:
8986 llvm_unreachable("TDK_success while diagnosing bad deduction");
8987
8988 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008989 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00008990 S.Diag(Templated->getLocation(),
8991 diag::note_ovl_candidate_incomplete_deduction)
8992 << ParamD->getDeclName();
8993 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008994 return;
8995 }
8996
John McCall42d7d192010-08-05 09:05:08 +00008997 case Sema::TDK_Underqualified: {
8998 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8999 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9000
Larisse Voufo98b20f12013-07-19 23:00:19 +00009001 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009002
9003 // Param will have been canonicalized, but it should just be a
9004 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009005 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009006 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009007 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009008 assert(S.Context.hasSameType(Param, NonCanonParam));
9009
9010 // Arg has also been canonicalized, but there's nothing we can do
9011 // about that. It also doesn't matter as much, because it won't
9012 // have any template parameters in it (because deduction isn't
9013 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009014 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009015
Larisse Voufo98b20f12013-07-19 23:00:19 +00009016 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9017 << ParamD->getDeclName() << Arg << NonCanonParam;
9018 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009019 return;
9020 }
9021
9022 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009023 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009024 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009025 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009026 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009027 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009028 which = 1;
9029 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009030 which = 2;
9031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009032
Larisse Voufo98b20f12013-07-19 23:00:19 +00009033 S.Diag(Templated->getLocation(),
9034 diag::note_ovl_candidate_inconsistent_deduction)
9035 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9036 << *DeductionFailure.getSecondArg();
9037 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009038 return;
9039 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009040
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009041 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009042 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009043 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009044 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009045 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009046 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009047 else {
9048 int index = 0;
9049 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9050 index = TTP->getIndex();
9051 else if (NonTypeTemplateParmDecl *NTTP
9052 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9053 index = NTTP->getIndex();
9054 else
9055 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009056 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009057 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009058 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009059 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009060 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009061 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009062
Douglas Gregor02eb4832010-05-08 18:13:28 +00009063 case Sema::TDK_TooManyArguments:
9064 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009065 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009066 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009067
9068 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009069 S.Diag(Templated->getLocation(),
9070 diag::note_ovl_candidate_instantiation_depth);
9071 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009072 return;
9073
9074 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009075 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009076 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009077 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009078 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009079 TemplateArgString = " ";
9080 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009081 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009082 }
9083
Richard Smith6f8d2c62012-05-09 05:17:00 +00009084 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009085 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009086 if (PDiag && PDiag->second.getDiagID() ==
9087 diag::err_typename_nested_not_found_enable_if) {
9088 // FIXME: Use the source range of the condition, and the fully-qualified
9089 // name of the enable_if template. These are both present in PDiag.
9090 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9091 << "'enable_if'" << TemplateArgString;
9092 return;
9093 }
9094
Richard Smith9ca64612012-05-07 09:03:25 +00009095 // Format the SFINAE diagnostic into the argument string.
9096 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9097 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009098 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009099 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009100 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009101 SFINAEArgString = ": ";
9102 R = SourceRange(PDiag->first, PDiag->first);
9103 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9104 }
9105
Larisse Voufo98b20f12013-07-19 23:00:19 +00009106 S.Diag(Templated->getLocation(),
9107 diag::note_ovl_candidate_substitution_failure)
9108 << TemplateArgString << SFINAEArgString << R;
9109 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009110 return;
9111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009112
Richard Smith8c6eeb92013-01-31 04:03:12 +00009113 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009114 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9115 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009116 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009117 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009118 return;
9119 }
9120
Richard Trieue3732352013-04-08 21:11:40 +00009121 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009122 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009123 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9124 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009125 if (FirstTA.getKind() == TemplateArgument::Template &&
9126 SecondTA.getKind() == TemplateArgument::Template) {
9127 TemplateName FirstTN = FirstTA.getAsTemplate();
9128 TemplateName SecondTN = SecondTA.getAsTemplate();
9129 if (FirstTN.getKind() == TemplateName::Template &&
9130 SecondTN.getKind() == TemplateName::Template) {
9131 if (FirstTN.getAsTemplateDecl()->getName() ==
9132 SecondTN.getAsTemplateDecl()->getName()) {
9133 // FIXME: This fixes a bad diagnostic where both templates are named
9134 // the same. This particular case is a bit difficult since:
9135 // 1) It is passed as a string to the diagnostic printer.
9136 // 2) The diagnostic printer only attempts to find a better
9137 // name for types, not decls.
9138 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009139 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009140 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9141 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9142 return;
9143 }
9144 }
9145 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00009146 // FIXME: For generic lambda parameters, check if the function is a lambda
9147 // call operator, and if so, emit a prettier and more informative
9148 // diagnostic that mentions 'auto' and lambda in addition to
9149 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009150 S.Diag(Templated->getLocation(),
9151 diag::note_ovl_candidate_non_deduced_mismatch)
9152 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009153 return;
Richard Trieue3732352013-04-08 21:11:40 +00009154 }
John McCall8b9ed552010-02-01 18:53:26 +00009155 // TODO: diagnose these individually, then kill off
9156 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009157 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009158 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9159 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009160 return;
9161 }
9162}
9163
Larisse Voufo98b20f12013-07-19 23:00:19 +00009164/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009165static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9166 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009167 unsigned TDK = Cand->DeductionFailure.Result;
9168 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9169 if (CheckArityMismatch(S, Cand, NumArgs))
9170 return;
9171 }
9172 DiagnoseBadDeduction(S, Cand->Function, // pattern
9173 Cand->DeductionFailure, NumArgs);
9174}
9175
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009176/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009177static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009178 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9179 FunctionDecl *Callee = Cand->Function;
9180
9181 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9182 CalleeTarget = S.IdentifyCUDATarget(Callee);
9183
9184 std::string FnDesc;
9185 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9186
9187 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009188 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9189
9190 // This could be an implicit constructor for which we could not infer the
9191 // target due to a collsion. Diagnose that case.
9192 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9193 if (Meth != nullptr && Meth->isImplicit()) {
9194 CXXRecordDecl *ParentClass = Meth->getParent();
9195 Sema::CXXSpecialMember CSM;
9196
9197 switch (FnKind) {
9198 default:
9199 return;
9200 case oc_implicit_default_constructor:
9201 CSM = Sema::CXXDefaultConstructor;
9202 break;
9203 case oc_implicit_copy_constructor:
9204 CSM = Sema::CXXCopyConstructor;
9205 break;
9206 case oc_implicit_move_constructor:
9207 CSM = Sema::CXXMoveConstructor;
9208 break;
9209 case oc_implicit_copy_assignment:
9210 CSM = Sema::CXXCopyAssignment;
9211 break;
9212 case oc_implicit_move_assignment:
9213 CSM = Sema::CXXMoveAssignment;
9214 break;
9215 };
9216
9217 bool ConstRHS = false;
9218 if (Meth->getNumParams()) {
9219 if (const ReferenceType *RT =
9220 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9221 ConstRHS = RT->getPointeeType().isConstQualified();
9222 }
9223 }
9224
9225 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9226 /* ConstRHS */ ConstRHS,
9227 /* Diagnose */ true);
9228 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009229}
9230
Richard Smith17c00b42014-11-12 01:24:00 +00009231static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009232 FunctionDecl *Callee = Cand->Function;
9233 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9234
9235 S.Diag(Callee->getLocation(),
9236 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9237 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9238}
9239
John McCall8b9ed552010-02-01 18:53:26 +00009240/// Generates a 'note' diagnostic for an overload candidate. We've
9241/// already generated a primary error at the call site.
9242///
9243/// It really does need to be a single diagnostic with its caret
9244/// pointed at the candidate declaration. Yes, this creates some
9245/// major challenges of technical writing. Yes, this makes pointing
9246/// out problems with specific arguments quite awkward. It's still
9247/// better than generating twenty screens of text for every failed
9248/// overload.
9249///
9250/// It would be great to be able to express per-candidate problems
9251/// more richly for those diagnostic clients that cared, but we'd
9252/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009253static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9254 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009255 FunctionDecl *Fn = Cand->Function;
9256
John McCall12f97bc2010-01-08 04:41:39 +00009257 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009258 if (Cand->Viable && (Fn->isDeleted() ||
9259 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009260 std::string FnDesc;
9261 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009262
9263 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009264 << FnKind << FnDesc
9265 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009266 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009267 return;
John McCall12f97bc2010-01-08 04:41:39 +00009268 }
9269
John McCalle1ac8d12010-01-13 00:25:19 +00009270 // We don't really have anything else to say about viable candidates.
9271 if (Cand->Viable) {
9272 S.NoteOverloadCandidate(Fn);
9273 return;
9274 }
John McCall0d1da222010-01-12 00:44:57 +00009275
John McCall6a61b522010-01-13 09:16:55 +00009276 switch (Cand->FailureKind) {
9277 case ovl_fail_too_many_arguments:
9278 case ovl_fail_too_few_arguments:
9279 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009280
John McCall6a61b522010-01-13 09:16:55 +00009281 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009282 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009283
John McCall578a1f82014-12-14 01:46:53 +00009284 case ovl_fail_illegal_constructor: {
9285 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9286 << (Fn->getPrimaryTemplate() ? 1 : 0);
9287 MaybeEmitInheritedConstructorNote(S, Fn);
9288 return;
9289 }
9290
John McCallfe796dd2010-01-23 05:17:32 +00009291 case ovl_fail_trivial_conversion:
9292 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009293 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009294 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009295
John McCall65eb8792010-02-25 01:37:24 +00009296 case ovl_fail_bad_conversion: {
9297 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009298 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009299 if (Cand->Conversions[I].isBad())
9300 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009301
John McCall6a61b522010-01-13 09:16:55 +00009302 // FIXME: this currently happens when we're called from SemaInit
9303 // when user-conversion overload fails. Figure out how to handle
9304 // those conditions and diagnose them well.
9305 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009306 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009307
9308 case ovl_fail_bad_target:
9309 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009310
9311 case ovl_fail_enable_if:
9312 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009313 }
John McCalld3224162010-01-08 00:58:21 +00009314}
9315
Richard Smith17c00b42014-11-12 01:24:00 +00009316static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009317 // Desugar the type of the surrogate down to a function type,
9318 // retaining as many typedefs as possible while still showing
9319 // the function type (and, therefore, its parameter types).
9320 QualType FnType = Cand->Surrogate->getConversionType();
9321 bool isLValueReference = false;
9322 bool isRValueReference = false;
9323 bool isPointer = false;
9324 if (const LValueReferenceType *FnTypeRef =
9325 FnType->getAs<LValueReferenceType>()) {
9326 FnType = FnTypeRef->getPointeeType();
9327 isLValueReference = true;
9328 } else if (const RValueReferenceType *FnTypeRef =
9329 FnType->getAs<RValueReferenceType>()) {
9330 FnType = FnTypeRef->getPointeeType();
9331 isRValueReference = true;
9332 }
9333 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9334 FnType = FnTypePtr->getPointeeType();
9335 isPointer = true;
9336 }
9337 // Desugar down to a function type.
9338 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9339 // Reconstruct the pointer/reference as appropriate.
9340 if (isPointer) FnType = S.Context.getPointerType(FnType);
9341 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9342 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9343
9344 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9345 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009346 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009347}
9348
Richard Smith17c00b42014-11-12 01:24:00 +00009349static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9350 SourceLocation OpLoc,
9351 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009352 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009353 std::string TypeStr("operator");
9354 TypeStr += Opc;
9355 TypeStr += "(";
9356 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009357 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009358 TypeStr += ")";
9359 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9360 } else {
9361 TypeStr += ", ";
9362 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9363 TypeStr += ")";
9364 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9365 }
9366}
9367
Richard Smith17c00b42014-11-12 01:24:00 +00009368static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9369 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009370 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009371 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9372 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009373 if (ICS.isBad()) break; // all meaningless after first invalid
9374 if (!ICS.isAmbiguous()) continue;
9375
John McCall5c32be02010-08-24 20:38:10 +00009376 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009377 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009378 }
9379}
9380
Larisse Voufo98b20f12013-07-19 23:00:19 +00009381static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009382 if (Cand->Function)
9383 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009384 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009385 return Cand->Surrogate->getLocation();
9386 return SourceLocation();
9387}
9388
Larisse Voufo98b20f12013-07-19 23:00:19 +00009389static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009390 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009391 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009392 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009393
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009394 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009395 case Sema::TDK_Incomplete:
9396 return 1;
9397
9398 case Sema::TDK_Underqualified:
9399 case Sema::TDK_Inconsistent:
9400 return 2;
9401
9402 case Sema::TDK_SubstitutionFailure:
9403 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009404 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009405 return 3;
9406
9407 case Sema::TDK_InstantiationDepth:
9408 case Sema::TDK_FailedOverloadResolution:
9409 return 4;
9410
9411 case Sema::TDK_InvalidExplicitArguments:
9412 return 5;
9413
9414 case Sema::TDK_TooManyArguments:
9415 case Sema::TDK_TooFewArguments:
9416 return 6;
9417 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009418 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009419}
9420
Richard Smith17c00b42014-11-12 01:24:00 +00009421namespace {
John McCallad2587a2010-01-12 00:48:53 +00009422struct CompareOverloadCandidatesForDisplay {
9423 Sema &S;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009424 size_t NumArgs;
9425
9426 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9427 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009428
9429 bool operator()(const OverloadCandidate *L,
9430 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009431 // Fast-path this check.
9432 if (L == R) return false;
9433
John McCall12f97bc2010-01-08 04:41:39 +00009434 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009435 if (L->Viable) {
9436 if (!R->Viable) return true;
9437
9438 // TODO: introduce a tri-valued comparison for overload
9439 // candidates. Would be more worthwhile if we had a sort
9440 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009441 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9442 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009443 } else if (R->Viable)
9444 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009445
John McCall3712d9e2010-01-15 23:32:50 +00009446 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009447
John McCall3712d9e2010-01-15 23:32:50 +00009448 // Criteria by which we can sort non-viable candidates:
9449 if (!L->Viable) {
9450 // 1. Arity mismatches come after other candidates.
9451 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009452 L->FailureKind == ovl_fail_too_few_arguments) {
9453 if (R->FailureKind == ovl_fail_too_many_arguments ||
9454 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009455 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9456 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9457 if (LDist == RDist) {
9458 if (L->FailureKind == R->FailureKind)
9459 // Sort non-surrogates before surrogates.
9460 return !L->IsSurrogate && R->IsSurrogate;
9461 // Sort candidates requiring fewer parameters than there were
9462 // arguments given after candidates requiring more parameters
9463 // than there were arguments given.
9464 return L->FailureKind == ovl_fail_too_many_arguments;
9465 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009466 return LDist < RDist;
9467 }
John McCall3712d9e2010-01-15 23:32:50 +00009468 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009469 }
John McCall3712d9e2010-01-15 23:32:50 +00009470 if (R->FailureKind == ovl_fail_too_many_arguments ||
9471 R->FailureKind == ovl_fail_too_few_arguments)
9472 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009473
John McCallfe796dd2010-01-23 05:17:32 +00009474 // 2. Bad conversions come first and are ordered by the number
9475 // of bad conversions and quality of good conversions.
9476 if (L->FailureKind == ovl_fail_bad_conversion) {
9477 if (R->FailureKind != ovl_fail_bad_conversion)
9478 return true;
9479
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009480 // The conversion that can be fixed with a smaller number of changes,
9481 // comes first.
9482 unsigned numLFixes = L->Fix.NumConversionsFixed;
9483 unsigned numRFixes = R->Fix.NumConversionsFixed;
9484 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9485 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009486 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009487 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009488 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009489
John McCallfe796dd2010-01-23 05:17:32 +00009490 // If there's any ordering between the defined conversions...
9491 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009492 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009493
9494 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009495 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009496 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009497 switch (CompareImplicitConversionSequences(S,
9498 L->Conversions[I],
9499 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009500 case ImplicitConversionSequence::Better:
9501 leftBetter++;
9502 break;
9503
9504 case ImplicitConversionSequence::Worse:
9505 leftBetter--;
9506 break;
9507
9508 case ImplicitConversionSequence::Indistinguishable:
9509 break;
9510 }
9511 }
9512 if (leftBetter > 0) return true;
9513 if (leftBetter < 0) return false;
9514
9515 } else if (R->FailureKind == ovl_fail_bad_conversion)
9516 return false;
9517
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009518 if (L->FailureKind == ovl_fail_bad_deduction) {
9519 if (R->FailureKind != ovl_fail_bad_deduction)
9520 return true;
9521
9522 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9523 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009524 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009525 } else if (R->FailureKind == ovl_fail_bad_deduction)
9526 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009527
John McCall3712d9e2010-01-15 23:32:50 +00009528 // TODO: others?
9529 }
9530
9531 // Sort everything else by location.
9532 SourceLocation LLoc = GetLocationForCandidate(L);
9533 SourceLocation RLoc = GetLocationForCandidate(R);
9534
9535 // Put candidates without locations (e.g. builtins) at the end.
9536 if (LLoc.isInvalid()) return false;
9537 if (RLoc.isInvalid()) return true;
9538
9539 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009540 }
9541};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009542}
John McCall12f97bc2010-01-08 04:41:39 +00009543
John McCallfe796dd2010-01-23 05:17:32 +00009544/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009545/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009546static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9547 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009548 assert(!Cand->Viable);
9549
9550 // Don't do anything on failures other than bad conversion.
9551 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9552
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009553 // We only want the FixIts if all the arguments can be corrected.
9554 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009555 // Use a implicit copy initialization to check conversion fixes.
9556 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009557
John McCallfe796dd2010-01-23 05:17:32 +00009558 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009559 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009560 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009561 while (true) {
9562 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9563 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009564 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009565 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009566 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009567 }
John McCallfe796dd2010-01-23 05:17:32 +00009568 }
9569
9570 if (ConvIdx == ConvCount)
9571 return;
9572
John McCall65eb8792010-02-25 01:37:24 +00009573 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9574 "remaining conversion is initialized?");
9575
Douglas Gregoradc7a702010-04-16 17:45:54 +00009576 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009577 // operation somehow.
9578 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009579
9580 const FunctionProtoType* Proto;
9581 unsigned ArgIdx = ConvIdx;
9582
9583 if (Cand->IsSurrogate) {
9584 QualType ConvType
9585 = Cand->Surrogate->getConversionType().getNonReferenceType();
9586 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9587 ConvType = ConvPtrType->getPointeeType();
9588 Proto = ConvType->getAs<FunctionProtoType>();
9589 ArgIdx--;
9590 } else if (Cand->Function) {
9591 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9592 if (isa<CXXMethodDecl>(Cand->Function) &&
9593 !isa<CXXConstructorDecl>(Cand->Function))
9594 ArgIdx--;
9595 } else {
9596 // Builtin binary operator with a bad first conversion.
9597 assert(ConvCount <= 3);
9598 for (; ConvIdx != ConvCount; ++ConvIdx)
9599 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009600 = TryCopyInitialization(S, Args[ConvIdx],
9601 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009602 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009603 /*InOverloadResolution*/ true,
9604 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009605 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009606 return;
9607 }
9608
9609 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009610 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009611 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009612 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009613 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9614 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9615 /*InOverloadResolution=*/true,
9616 /*AllowObjCWritebackConversion=*/
9617 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009618 // Store the FixIt in the candidate if it exists.
9619 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009620 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009621 }
John McCallfe796dd2010-01-23 05:17:32 +00009622 else
9623 Cand->Conversions[ConvIdx].setEllipsis();
9624 }
9625}
9626
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009627/// PrintOverloadCandidates - When overload resolution fails, prints
9628/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009629/// set.
John McCall5c32be02010-08-24 20:38:10 +00009630void OverloadCandidateSet::NoteCandidates(Sema &S,
9631 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009632 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009633 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009634 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009635 // Sort the candidates by viability and position. Sorting directly would
9636 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009637 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009638 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9639 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009640 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009641 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009642 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009643 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009644 if (Cand->Function || Cand->IsSurrogate)
9645 Cands.push_back(Cand);
9646 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9647 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009648 }
9649 }
9650
John McCallad2587a2010-01-12 00:48:53 +00009651 std::sort(Cands.begin(), Cands.end(),
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009652 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009653
John McCall0d1da222010-01-12 00:44:57 +00009654 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009655
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009656 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009657 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009658 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009659 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9660 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009661
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009662 // Set an arbitrary limit on the number of candidate functions we'll spam
9663 // the user with. FIXME: This limit should depend on details of the
9664 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009665 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009666 break;
9667 }
9668 ++CandsShown;
9669
John McCalld3224162010-01-08 00:58:21 +00009670 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009671 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009672 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009673 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009674 else {
9675 assert(Cand->Viable &&
9676 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009677 // Generally we only see ambiguities including viable builtin
9678 // operators if overload resolution got screwed up by an
9679 // ambiguous user-defined conversion.
9680 //
9681 // FIXME: It's quite possible for different conversions to see
9682 // different ambiguities, though.
9683 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009684 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009685 ReportedAmbiguousConversions = true;
9686 }
John McCalld3224162010-01-08 00:58:21 +00009687
John McCall0d1da222010-01-12 00:44:57 +00009688 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009689 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009690 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009691 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009692
9693 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009694 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009695}
9696
Larisse Voufo98b20f12013-07-19 23:00:19 +00009697static SourceLocation
9698GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9699 return Cand->Specialization ? Cand->Specialization->getLocation()
9700 : SourceLocation();
9701}
9702
Richard Smith17c00b42014-11-12 01:24:00 +00009703namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009704struct CompareTemplateSpecCandidatesForDisplay {
9705 Sema &S;
9706 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9707
9708 bool operator()(const TemplateSpecCandidate *L,
9709 const TemplateSpecCandidate *R) {
9710 // Fast-path this check.
9711 if (L == R)
9712 return false;
9713
9714 // Assuming that both candidates are not matches...
9715
9716 // Sort by the ranking of deduction failures.
9717 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9718 return RankDeductionFailure(L->DeductionFailure) <
9719 RankDeductionFailure(R->DeductionFailure);
9720
9721 // Sort everything else by location.
9722 SourceLocation LLoc = GetLocationForCandidate(L);
9723 SourceLocation RLoc = GetLocationForCandidate(R);
9724
9725 // Put candidates without locations (e.g. builtins) at the end.
9726 if (LLoc.isInvalid())
9727 return false;
9728 if (RLoc.isInvalid())
9729 return true;
9730
9731 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9732 }
9733};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009734}
Larisse Voufo98b20f12013-07-19 23:00:19 +00009735
9736/// Diagnose a template argument deduction failure.
9737/// We are treating these failures as overload failures due to bad
9738/// deductions.
9739void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9740 DiagnoseBadDeduction(S, Specialization, // pattern
9741 DeductionFailure, /*NumArgs=*/0);
9742}
9743
9744void TemplateSpecCandidateSet::destroyCandidates() {
9745 for (iterator i = begin(), e = end(); i != e; ++i) {
9746 i->DeductionFailure.Destroy();
9747 }
9748}
9749
9750void TemplateSpecCandidateSet::clear() {
9751 destroyCandidates();
9752 Candidates.clear();
9753}
9754
9755/// NoteCandidates - When no template specialization match is found, prints
9756/// diagnostic messages containing the non-matching specializations that form
9757/// the candidate set.
9758/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9759/// OCD == OCD_AllCandidates and Cand->Viable == false.
9760void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9761 // Sort the candidates by position (assuming no candidate is a match).
9762 // Sorting directly would be prohibitive, so we make a set of pointers
9763 // and sort those.
9764 SmallVector<TemplateSpecCandidate *, 32> Cands;
9765 Cands.reserve(size());
9766 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9767 if (Cand->Specialization)
9768 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009769 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009770 // in general, want to list every possible builtin candidate.
9771 }
9772
9773 std::sort(Cands.begin(), Cands.end(),
9774 CompareTemplateSpecCandidatesForDisplay(S));
9775
9776 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9777 // for generalization purposes (?).
9778 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9779
9780 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9781 unsigned CandsShown = 0;
9782 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9783 TemplateSpecCandidate *Cand = *I;
9784
9785 // Set an arbitrary limit on the number of candidates we'll spam
9786 // the user with. FIXME: This limit should depend on details of the
9787 // candidate list.
9788 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9789 break;
9790 ++CandsShown;
9791
9792 assert(Cand->Specialization &&
9793 "Non-matching built-in candidates are not added to Cands.");
9794 Cand->NoteDeductionFailure(S);
9795 }
9796
9797 if (I != E)
9798 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9799}
9800
Douglas Gregorb491ed32011-02-19 21:32:49 +00009801// [PossiblyAFunctionType] --> [Return]
9802// NonFunctionType --> NonFunctionType
9803// R (A) --> R(A)
9804// R (*)(A) --> R (A)
9805// R (&)(A) --> R (A)
9806// R (S::*)(A) --> R (A)
9807QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9808 QualType Ret = PossiblyAFunctionType;
9809 if (const PointerType *ToTypePtr =
9810 PossiblyAFunctionType->getAs<PointerType>())
9811 Ret = ToTypePtr->getPointeeType();
9812 else if (const ReferenceType *ToTypeRef =
9813 PossiblyAFunctionType->getAs<ReferenceType>())
9814 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009815 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009816 PossiblyAFunctionType->getAs<MemberPointerType>())
9817 Ret = MemTypePtr->getPointeeType();
9818 Ret =
9819 Context.getCanonicalType(Ret).getUnqualifiedType();
9820 return Ret;
9821}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009822
Richard Smith17c00b42014-11-12 01:24:00 +00009823namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009824// A helper class to help with address of function resolution
9825// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +00009826class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009827 Sema& S;
9828 Expr* SourceExpr;
9829 const QualType& TargetType;
9830 QualType TargetFunctionType; // Extracted function type from target type
9831
9832 bool Complain;
9833 //DeclAccessPair& ResultFunctionAccessPair;
9834 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009835
Douglas Gregorb491ed32011-02-19 21:32:49 +00009836 bool TargetTypeIsNonStaticMemberFunction;
9837 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009838 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009839
Douglas Gregorb491ed32011-02-19 21:32:49 +00009840 OverloadExpr::FindResult OvlExprInfo;
9841 OverloadExpr *OvlExpr;
9842 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009843 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009844 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009845
Douglas Gregorb491ed32011-02-19 21:32:49 +00009846public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009847 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9848 const QualType &TargetType, bool Complain)
9849 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9850 Complain(Complain), Context(S.getASTContext()),
9851 TargetTypeIsNonStaticMemberFunction(
9852 !!TargetType->getAs<MemberPointerType>()),
9853 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009854 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009855 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9856 OvlExpr(OvlExprInfo.Expression),
9857 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009858 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009859
David Majnemera4f7c7a2013-08-01 06:13:59 +00009860 if (TargetFunctionType->isFunctionType()) {
9861 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9862 if (!UME->isImplicitAccess() &&
9863 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9864 StaticMemberFunctionFromBoundPointer = true;
9865 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9866 DeclAccessPair dap;
9867 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9868 OvlExpr, false, &dap)) {
9869 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9870 if (!Method->isStatic()) {
9871 // If the target type is a non-function type and the function found
9872 // is a non-static member function, pretend as if that was the
9873 // target, it's the only possible type to end up with.
9874 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009875
David Majnemera4f7c7a2013-08-01 06:13:59 +00009876 // And skip adding the function if its not in the proper form.
9877 // We'll diagnose this due to an empty set of functions.
9878 if (!OvlExprInfo.HasFormOfMemberPointer)
9879 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009880 }
9881
David Majnemera4f7c7a2013-08-01 06:13:59 +00009882 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009883 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009884 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009885 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009886
9887 if (OvlExpr->hasExplicitTemplateArgs())
9888 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009889
Douglas Gregorb491ed32011-02-19 21:32:49 +00009890 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9891 // C++ [over.over]p4:
9892 // If more than one function is selected, [...]
9893 if (Matches.size() > 1) {
9894 if (FoundNonTemplateFunction)
9895 EliminateAllTemplateMatches();
9896 else
9897 EliminateAllExceptMostSpecializedTemplate();
9898 }
9899 }
9900 }
9901
9902private:
9903 bool isTargetTypeAFunction() const {
9904 return TargetFunctionType->isFunctionType();
9905 }
9906
9907 // [ToType] [Return]
9908
9909 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9910 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9911 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9912 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9913 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9914 }
9915
9916 // return true if any matching specializations were found
9917 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9918 const DeclAccessPair& CurAccessFunPair) {
9919 if (CXXMethodDecl *Method
9920 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9921 // Skip non-static function templates when converting to pointer, and
9922 // static when converting to member pointer.
9923 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9924 return false;
9925 }
9926 else if (TargetTypeIsNonStaticMemberFunction)
9927 return false;
9928
9929 // C++ [over.over]p2:
9930 // If the name is a function template, template argument deduction is
9931 // done (14.8.2.2), and if the argument deduction succeeds, the
9932 // resulting template argument list is used to generate a single
9933 // function template specialization, which is added to the set of
9934 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +00009935 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009936 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009937 if (Sema::TemplateDeductionResult Result
9938 = S.DeduceTemplateArguments(FunctionTemplate,
9939 &OvlExplicitTemplateArgs,
9940 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009941 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009942 // Make a note of the failed deduction for diagnostics.
9943 FailedCandidates.addCandidate()
9944 .set(FunctionTemplate->getTemplatedDecl(),
9945 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009946 return false;
9947 }
9948
Douglas Gregor19a41f12013-04-17 08:45:07 +00009949 // Template argument deduction ensures that we have an exact match or
9950 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009951 // This function template specicalization works.
9952 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009953 assert(S.isSameOrCompatibleFunctionType(
9954 Context.getCanonicalType(Specialization->getType()),
9955 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009956 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9957 return true;
9958 }
9959
9960 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9961 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009962 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009963 // Skip non-static functions when converting to pointer, and static
9964 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009965 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9966 return false;
9967 }
9968 else if (TargetTypeIsNonStaticMemberFunction)
9969 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009970
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009971 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009972 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009973 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009974 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009975 return false;
9976
Richard Smith2a7d4812013-05-04 07:00:32 +00009977 // If any candidate has a placeholder return type, trigger its deduction
9978 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00009979 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +00009980 FunDecl->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00009981 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9982 return false;
9983
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009984 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009985 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9986 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009987 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9988 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009989 Matches.push_back(std::make_pair(CurAccessFunPair,
9990 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009991 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009992 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009993 }
Mike Stump11289f42009-09-09 15:08:12 +00009994 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009995
9996 return false;
9997 }
9998
9999 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10000 bool Ret = false;
10001
10002 // If the overload expression doesn't have the form of a pointer to
10003 // member, don't try to convert it to a pointer-to-member type.
10004 if (IsInvalidFormOfPointerToMemberFunction())
10005 return false;
10006
10007 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10008 E = OvlExpr->decls_end();
10009 I != E; ++I) {
10010 // Look through any using declarations to find the underlying function.
10011 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10012
10013 // C++ [over.over]p3:
10014 // Non-member functions and static member functions match
10015 // targets of type "pointer-to-function" or "reference-to-function."
10016 // Nonstatic member functions match targets of
10017 // type "pointer-to-member-function."
10018 // Note that according to DR 247, the containing class does not matter.
10019 if (FunctionTemplateDecl *FunctionTemplate
10020 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10021 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10022 Ret = true;
10023 }
10024 // If we have explicit template arguments supplied, skip non-templates.
10025 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10026 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10027 Ret = true;
10028 }
10029 assert(Ret || Matches.empty());
10030 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010031 }
10032
Douglas Gregorb491ed32011-02-19 21:32:49 +000010033 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010034 // [...] and any given function template specialization F1 is
10035 // eliminated if the set contains a second function template
10036 // specialization whose function template is more specialized
10037 // than the function template of F1 according to the partial
10038 // ordering rules of 14.5.5.2.
10039
10040 // The algorithm specified above is quadratic. We instead use a
10041 // two-pass algorithm (similar to the one used to identify the
10042 // best viable function in an overload set) that identifies the
10043 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010044
10045 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10046 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10047 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010048
Larisse Voufo98b20f12013-07-19 23:00:19 +000010049 // TODO: It looks like FailedCandidates does not serve much purpose
10050 // here, since the no_viable diagnostic has index 0.
10051 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010052 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010053 SourceExpr->getLocStart(), S.PDiag(),
10054 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10055 .second->getDeclName(),
10056 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10057 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010058
Douglas Gregorb491ed32011-02-19 21:32:49 +000010059 if (Result != MatchesCopy.end()) {
10060 // Make it the first and only element
10061 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10062 Matches[0].second = cast<FunctionDecl>(*Result);
10063 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +000010064 }
10065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010066
Douglas Gregorb491ed32011-02-19 21:32:49 +000010067 void EliminateAllTemplateMatches() {
10068 // [...] any function template specializations in the set are
10069 // eliminated if the set also contains a non-template function, [...]
10070 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010071 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010072 ++I;
10073 else {
10074 Matches[I] = Matches[--N];
10075 Matches.set_size(N);
10076 }
10077 }
10078 }
10079
10080public:
10081 void ComplainNoMatchesFound() const {
10082 assert(Matches.empty());
10083 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10084 << OvlExpr->getName() << TargetFunctionType
10085 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010086 if (FailedCandidates.empty())
10087 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10088 else {
10089 // We have some deduction failure messages. Use them to diagnose
10090 // the function templates, and diagnose the non-template candidates
10091 // normally.
10092 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10093 IEnd = OvlExpr->decls_end();
10094 I != IEnd; ++I)
10095 if (FunctionDecl *Fun =
10096 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10097 S.NoteOverloadCandidate(Fun, TargetFunctionType);
10098 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10099 }
10100 }
10101
Douglas Gregorb491ed32011-02-19 21:32:49 +000010102 bool IsInvalidFormOfPointerToMemberFunction() const {
10103 return TargetTypeIsNonStaticMemberFunction &&
10104 !OvlExprInfo.HasFormOfMemberPointer;
10105 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010106
Douglas Gregorb491ed32011-02-19 21:32:49 +000010107 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10108 // TODO: Should we condition this on whether any functions might
10109 // have matched, or is it more appropriate to do that in callers?
10110 // TODO: a fixit wouldn't hurt.
10111 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10112 << TargetType << OvlExpr->getSourceRange();
10113 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010114
10115 bool IsStaticMemberFunctionFromBoundPointer() const {
10116 return StaticMemberFunctionFromBoundPointer;
10117 }
10118
10119 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10120 S.Diag(OvlExpr->getLocStart(),
10121 diag::err_invalid_form_pointer_member_function)
10122 << OvlExpr->getSourceRange();
10123 }
10124
Douglas Gregorb491ed32011-02-19 21:32:49 +000010125 void ComplainOfInvalidConversion() const {
10126 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10127 << OvlExpr->getName() << TargetType;
10128 }
10129
10130 void ComplainMultipleMatchesFound() const {
10131 assert(Matches.size() > 1);
10132 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10133 << OvlExpr->getName()
10134 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +000010135 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010136 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010137
10138 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10139
Douglas Gregorb491ed32011-02-19 21:32:49 +000010140 int getNumMatches() const { return Matches.size(); }
10141
10142 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010143 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010144 return Matches[0].second;
10145 }
10146
10147 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010148 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010149 return &Matches[0].first;
10150 }
10151};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010152}
Richard Smith17c00b42014-11-12 01:24:00 +000010153
Douglas Gregorb491ed32011-02-19 21:32:49 +000010154/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10155/// an overloaded function (C++ [over.over]), where @p From is an
10156/// expression with overloaded function type and @p ToType is the type
10157/// we're trying to resolve to. For example:
10158///
10159/// @code
10160/// int f(double);
10161/// int f(int);
10162///
10163/// int (*pfd)(double) = f; // selects f(double)
10164/// @endcode
10165///
10166/// This routine returns the resulting FunctionDecl if it could be
10167/// resolved, and NULL otherwise. When @p Complain is true, this
10168/// routine will emit diagnostics if there is an error.
10169FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010170Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10171 QualType TargetType,
10172 bool Complain,
10173 DeclAccessPair &FoundResult,
10174 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010175 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010176
10177 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10178 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010179 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010180 FunctionDecl *Fn = nullptr;
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010181 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010182 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10183 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10184 else
10185 Resolver.ComplainNoMatchesFound();
10186 }
10187 else if (NumMatches > 1 && Complain)
10188 Resolver.ComplainMultipleMatchesFound();
10189 else if (NumMatches == 1) {
10190 Fn = Resolver.getMatchingFunctionDecl();
10191 assert(Fn);
10192 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010193 if (Complain) {
10194 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10195 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10196 else
10197 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10198 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010199 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010200
10201 if (pHadMultipleCandidates)
10202 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010203 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010204}
10205
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010206/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010207/// resolve that overloaded function expression down to a single function.
10208///
10209/// This routine can only resolve template-ids that refer to a single function
10210/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010211/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010212/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010213///
10214/// If no template-ids are found, no diagnostics are emitted and NULL is
10215/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010216FunctionDecl *
10217Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10218 bool Complain,
10219 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010220 // C++ [over.over]p1:
10221 // [...] [Note: any redundant set of parentheses surrounding the
10222 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010223 // C++ [over.over]p1:
10224 // [...] The overloaded function name can be preceded by the &
10225 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010226
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010227 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010228 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010229 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010230
10231 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010232 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010233 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010234
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010235 // Look through all of the overloaded functions, searching for one
10236 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010237 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010238 for (UnresolvedSetIterator I = ovl->decls_begin(),
10239 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010240 // C++0x [temp.arg.explicit]p3:
10241 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010242 // where deduction is not done, if a template argument list is
10243 // specified and it, along with any default template arguments,
10244 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010245 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010246 FunctionTemplateDecl *FunctionTemplate
10247 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010248
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010249 // C++ [over.over]p2:
10250 // If the name is a function template, template argument deduction is
10251 // done (14.8.2.2), and if the argument deduction succeeds, the
10252 // resulting template argument list is used to generate a single
10253 // function template specialization, which is added to the set of
10254 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010255 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010256 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010257 if (TemplateDeductionResult Result
10258 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010259 Specialization, Info,
10260 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010261 // Make a note of the failed deduction for diagnostics.
10262 // TODO: Actually use the failed-deduction info?
10263 FailedCandidates.addCandidate()
10264 .set(FunctionTemplate->getTemplatedDecl(),
10265 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010266 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010267 }
10268
John McCall0009fcc2011-04-26 20:42:42 +000010269 assert(Specialization && "no specialization and no error?");
10270
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010271 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010272 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010273 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010274 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10275 << ovl->getName();
10276 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010277 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010278 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010279 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010280
John McCall0009fcc2011-04-26 20:42:42 +000010281 Matched = Specialization;
10282 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010284
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010285 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010286 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010287 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010288 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010289
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010290 return Matched;
10291}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010292
Douglas Gregor1beec452011-03-12 01:48:56 +000010293
10294
10295
John McCall50a2c2c2011-10-11 23:14:30 +000010296// Resolve and fix an overloaded expression that can be resolved
10297// because it identifies a single function template specialization.
10298//
Douglas Gregor1beec452011-03-12 01:48:56 +000010299// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010300//
10301// Return true if it was logically possible to so resolve the
10302// expression, regardless of whether or not it succeeded. Always
10303// returns true if 'complain' is set.
10304bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10305 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10306 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010307 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010308 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010309 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010310
John McCall50a2c2c2011-10-11 23:14:30 +000010311 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010312
John McCall0009fcc2011-04-26 20:42:42 +000010313 DeclAccessPair found;
10314 ExprResult SingleFunctionExpression;
10315 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10316 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010317 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010318 SrcExpr = ExprError();
10319 return true;
10320 }
John McCall0009fcc2011-04-26 20:42:42 +000010321
10322 // It is only correct to resolve to an instance method if we're
10323 // resolving a form that's permitted to be a pointer to member.
10324 // Otherwise we'll end up making a bound member expression, which
10325 // is illegal in all the contexts we resolve like this.
10326 if (!ovl.HasFormOfMemberPointer &&
10327 isa<CXXMethodDecl>(fn) &&
10328 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010329 if (!complain) return false;
10330
10331 Diag(ovl.Expression->getExprLoc(),
10332 diag::err_bound_member_function)
10333 << 0 << ovl.Expression->getSourceRange();
10334
10335 // TODO: I believe we only end up here if there's a mix of
10336 // static and non-static candidates (otherwise the expression
10337 // would have 'bound member' type, not 'overload' type).
10338 // Ideally we would note which candidate was chosen and why
10339 // the static candidates were rejected.
10340 SrcExpr = ExprError();
10341 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010342 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010343
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010344 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010345 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010346 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010347
10348 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010349 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010350 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010351 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010352 if (SingleFunctionExpression.isInvalid()) {
10353 SrcExpr = ExprError();
10354 return true;
10355 }
10356 }
John McCall0009fcc2011-04-26 20:42:42 +000010357 }
10358
10359 if (!SingleFunctionExpression.isUsable()) {
10360 if (complain) {
10361 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10362 << ovl.Expression->getName()
10363 << DestTypeForComplaining
10364 << OpRangeForComplaining
10365 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010366 NoteAllOverloadCandidates(SrcExpr.get());
10367
10368 SrcExpr = ExprError();
10369 return true;
10370 }
10371
10372 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010373 }
10374
John McCall50a2c2c2011-10-11 23:14:30 +000010375 SrcExpr = SingleFunctionExpression;
10376 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010377}
10378
Douglas Gregorcabea402009-09-22 15:41:20 +000010379/// \brief Add a single candidate to the overload set.
10380static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010381 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010382 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010383 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010384 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010385 bool PartialOverloading,
10386 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010387 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010388 if (isa<UsingShadowDecl>(Callee))
10389 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10390
Douglas Gregorcabea402009-09-22 15:41:20 +000010391 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010392 if (ExplicitTemplateArgs) {
10393 assert(!KnownValid && "Explicit template arguments?");
10394 return;
10395 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010396 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10397 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010398 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010399 return;
John McCalld14a8642009-11-21 08:51:07 +000010400 }
10401
10402 if (FunctionTemplateDecl *FuncTemplate
10403 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010404 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010405 ExplicitTemplateArgs, Args, CandidateSet,
10406 /*SuppressUsedConversions=*/false,
10407 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010408 return;
10409 }
10410
Richard Smith95ce4f62011-06-26 22:19:54 +000010411 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010412}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010413
Douglas Gregorcabea402009-09-22 15:41:20 +000010414/// \brief Add the overload candidates named by callee and/or found by argument
10415/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010416void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010417 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010418 OverloadCandidateSet &CandidateSet,
10419 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010420
10421#ifndef NDEBUG
10422 // Verify that ArgumentDependentLookup is consistent with the rules
10423 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010424 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010425 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10426 // and let Y be the lookup set produced by argument dependent
10427 // lookup (defined as follows). If X contains
10428 //
10429 // -- a declaration of a class member, or
10430 //
10431 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010432 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010433 //
10434 // -- a declaration that is neither a function or a function
10435 // template
10436 //
10437 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010438
John McCall57500772009-12-16 12:17:52 +000010439 if (ULE->requiresADL()) {
10440 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10441 E = ULE->decls_end(); I != E; ++I) {
10442 assert(!(*I)->getDeclContext()->isRecord());
10443 assert(isa<UsingShadowDecl>(*I) ||
10444 !(*I)->getDeclContext()->isFunctionOrMethod());
10445 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010446 }
10447 }
10448#endif
10449
John McCall57500772009-12-16 12:17:52 +000010450 // It would be nice to avoid this copy.
10451 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010452 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010453 if (ULE->hasExplicitTemplateArgs()) {
10454 ULE->copyTemplateArgumentsInto(TABuffer);
10455 ExplicitTemplateArgs = &TABuffer;
10456 }
10457
10458 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10459 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010460 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10461 CandidateSet, PartialOverloading,
10462 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010463
John McCall57500772009-12-16 12:17:52 +000010464 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010465 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010466 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010467 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010468}
John McCalld681c392009-12-16 08:11:27 +000010469
Richard Smith0603bbb2013-06-12 22:56:54 +000010470/// Determine whether a declaration with the specified name could be moved into
10471/// a different namespace.
10472static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10473 switch (Name.getCXXOverloadedOperator()) {
10474 case OO_New: case OO_Array_New:
10475 case OO_Delete: case OO_Array_Delete:
10476 return false;
10477
10478 default:
10479 return true;
10480 }
10481}
10482
Richard Smith998a5912011-06-05 22:42:48 +000010483/// Attempt to recover from an ill-formed use of a non-dependent name in a
10484/// template, where the non-dependent name was declared after the template
10485/// was defined. This is common in code written for a compilers which do not
10486/// correctly implement two-stage name lookup.
10487///
10488/// Returns true if a viable candidate was found and a diagnostic was issued.
10489static bool
10490DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10491 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010492 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010493 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010494 ArrayRef<Expr *> Args,
10495 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010496 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10497 return false;
10498
10499 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010500 if (DC->isTransparentContext())
10501 continue;
10502
Richard Smith998a5912011-06-05 22:42:48 +000010503 SemaRef.LookupQualifiedName(R, DC);
10504
10505 if (!R.empty()) {
10506 R.suppressDiagnostics();
10507
10508 if (isa<CXXRecordDecl>(DC)) {
10509 // Don't diagnose names we find in classes; we get much better
10510 // diagnostics for these from DiagnoseEmptyLookup.
10511 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000010512 if (DoDiagnoseEmptyLookup)
10513 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000010514 return false;
10515 }
10516
Richard Smith100b24a2014-04-17 01:52:14 +000010517 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010518 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10519 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010520 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010521 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010522
10523 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010524 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010525 // No viable functions. Don't bother the user with notes for functions
10526 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010527 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010528 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010529 }
Richard Smith998a5912011-06-05 22:42:48 +000010530
10531 // Find the namespaces where ADL would have looked, and suggest
10532 // declaring the function there instead.
10533 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10534 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010535 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010536 AssociatedNamespaces,
10537 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010538 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010539 if (canBeDeclaredInNamespace(R.getLookupName())) {
10540 DeclContext *Std = SemaRef.getStdNamespace();
10541 for (Sema::AssociatedNamespaceSet::iterator
10542 it = AssociatedNamespaces.begin(),
10543 end = AssociatedNamespaces.end(); it != end; ++it) {
10544 // Never suggest declaring a function within namespace 'std'.
10545 if (Std && Std->Encloses(*it))
10546 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010547
Richard Smith0603bbb2013-06-12 22:56:54 +000010548 // Never suggest declaring a function within a namespace with a
10549 // reserved name, like __gnu_cxx.
10550 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10551 if (NS &&
10552 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10553 continue;
10554
10555 SuggestedNamespaces.insert(*it);
10556 }
Richard Smith998a5912011-06-05 22:42:48 +000010557 }
10558
10559 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10560 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010561 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010562 SemaRef.Diag(Best->Function->getLocation(),
10563 diag::note_not_found_by_two_phase_lookup)
10564 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010565 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010566 SemaRef.Diag(Best->Function->getLocation(),
10567 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010568 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010569 } else {
10570 // FIXME: It would be useful to list the associated namespaces here,
10571 // but the diagnostics infrastructure doesn't provide a way to produce
10572 // a localized representation of a list of items.
10573 SemaRef.Diag(Best->Function->getLocation(),
10574 diag::note_not_found_by_two_phase_lookup)
10575 << R.getLookupName() << 2;
10576 }
10577
10578 // Try to recover by calling this function.
10579 return true;
10580 }
10581
10582 R.clear();
10583 }
10584
10585 return false;
10586}
10587
10588/// Attempt to recover from ill-formed use of a non-dependent operator in a
10589/// template, where the non-dependent operator was declared after the template
10590/// was defined.
10591///
10592/// Returns true if a viable candidate was found and a diagnostic was issued.
10593static bool
10594DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10595 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010596 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010597 DeclarationName OpName =
10598 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10599 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10600 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010601 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010602 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010603}
10604
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010605namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010606class BuildRecoveryCallExprRAII {
10607 Sema &SemaRef;
10608public:
10609 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10610 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10611 SemaRef.IsBuildingRecoveryCallExpr = true;
10612 }
10613
10614 ~BuildRecoveryCallExprRAII() {
10615 SemaRef.IsBuildingRecoveryCallExpr = false;
10616 }
10617};
10618
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010619}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010620
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010621static std::unique_ptr<CorrectionCandidateCallback>
10622MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10623 bool HasTemplateArgs, bool AllowTypoCorrection) {
10624 if (!AllowTypoCorrection)
10625 return llvm::make_unique<NoTypoCorrectionCCC>();
10626 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10627 HasTemplateArgs, ME);
10628}
10629
John McCalld681c392009-12-16 08:11:27 +000010630/// Attempts to recover from a call where no functions were found.
10631///
10632/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010633static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010634BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010635 UnresolvedLookupExpr *ULE,
10636 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010637 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010638 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010639 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010640 // Do not try to recover if it is already building a recovery call.
10641 // This stops infinite loops for template instantiations like
10642 //
10643 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10644 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10645 //
10646 if (SemaRef.IsBuildingRecoveryCallExpr)
10647 return ExprError();
10648 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010649
10650 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010651 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010652 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010653
John McCall57500772009-12-16 12:17:52 +000010654 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010655 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010656 if (ULE->hasExplicitTemplateArgs()) {
10657 ULE->copyTemplateArgumentsInto(TABuffer);
10658 ExplicitTemplateArgs = &TABuffer;
10659 }
10660
John McCalld681c392009-12-16 08:11:27 +000010661 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10662 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000010663 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000010664 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000010665 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000010666 ExplicitTemplateArgs, Args,
10667 &DoDiagnoseEmptyLookup) &&
10668 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
10669 S, SS, R,
10670 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10671 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10672 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010673 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010674
John McCall57500772009-12-16 12:17:52 +000010675 assert(!R.empty() && "lookup results empty despite recovery");
10676
10677 // Build an implicit member call if appropriate. Just drop the
10678 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010679 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010680 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010681 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10682 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010683 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010684 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010685 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010686 else
10687 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10688
10689 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010690 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010691
10692 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010693 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010694 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010695 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010696 MultiExprArg(Args.data(), Args.size()),
10697 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010698}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010699
Sam Panzer0f384432012-08-21 00:52:01 +000010700/// \brief Constructs and populates an OverloadedCandidateSet from
10701/// the given function.
10702/// \returns true when an the ExprResult output parameter has been set.
10703bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10704 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010705 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010706 SourceLocation RParenLoc,
10707 OverloadCandidateSet *CandidateSet,
10708 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010709#ifndef NDEBUG
10710 if (ULE->requiresADL()) {
10711 // To do ADL, we must have found an unqualified name.
10712 assert(!ULE->getQualifier() && "qualified name with ADL");
10713
10714 // We don't perform ADL for implicit declarations of builtins.
10715 // Verify that this was correctly set up.
10716 FunctionDecl *F;
10717 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10718 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10719 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010720 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010721
John McCall57500772009-12-16 12:17:52 +000010722 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010723 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010724 }
John McCall57500772009-12-16 12:17:52 +000010725#endif
10726
John McCall4124c492011-10-17 18:40:02 +000010727 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010728 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010729 *Result = ExprError();
10730 return true;
10731 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010732
John McCall57500772009-12-16 12:17:52 +000010733 // Add the functions denoted by the callee to the set of candidate
10734 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010735 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010736
Hans Wennborgb2747382015-06-12 21:23:23 +000010737 if (getLangOpts().MSVCCompat &&
10738 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000010739 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10740
10741 OverloadCandidateSet::iterator Best;
10742 if (CandidateSet->empty() ||
10743 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
10744 OR_No_Viable_Function) {
10745 // In Microsoft mode, if we are inside a template class member function then
10746 // create a type dependent CallExpr. The goal is to postpone name lookup
10747 // to instantiation time to be able to search into type dependent base
10748 // classes.
10749 CallExpr *CE = new (Context) CallExpr(
10750 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010751 CE->setTypeDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010752 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000010753 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010754 }
Francois Pichetbcf64712011-09-07 00:14:57 +000010755 }
John McCalld681c392009-12-16 08:11:27 +000010756
Hans Wennborg64937c62015-06-11 21:21:57 +000010757 if (CandidateSet->empty())
10758 return false;
10759
John McCall4124c492011-10-17 18:40:02 +000010760 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010761 return false;
10762}
John McCall4124c492011-10-17 18:40:02 +000010763
Sam Panzer0f384432012-08-21 00:52:01 +000010764/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10765/// the completed call expression. If overload resolution fails, emits
10766/// diagnostics and returns ExprError()
10767static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10768 UnresolvedLookupExpr *ULE,
10769 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010770 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010771 SourceLocation RParenLoc,
10772 Expr *ExecConfig,
10773 OverloadCandidateSet *CandidateSet,
10774 OverloadCandidateSet::iterator *Best,
10775 OverloadingResult OverloadResult,
10776 bool AllowTypoCorrection) {
10777 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010778 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010779 RParenLoc, /*EmptyLookup=*/true,
10780 AllowTypoCorrection);
10781
10782 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010783 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010784 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010785 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010786 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10787 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010788 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010789 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10790 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010791 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010792
Richard Smith998a5912011-06-05 22:42:48 +000010793 case OR_No_Viable_Function: {
10794 // Try to recover by looking for viable functions which the user might
10795 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010796 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010797 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010798 /*EmptyLookup=*/false,
10799 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010800 if (!Recovery.isInvalid())
10801 return Recovery;
10802
Sam Panzer0f384432012-08-21 00:52:01 +000010803 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010804 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010805 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010806 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010807 break;
Richard Smith998a5912011-06-05 22:42:48 +000010808 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010809
10810 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010811 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010812 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010813 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010814 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010815
Sam Panzer0f384432012-08-21 00:52:01 +000010816 case OR_Deleted: {
10817 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10818 << (*Best)->Function->isDeleted()
10819 << ULE->getName()
10820 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10821 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010822 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010823
Sam Panzer0f384432012-08-21 00:52:01 +000010824 // We emitted an error for the unvailable/deleted function call but keep
10825 // the call in the AST.
10826 FunctionDecl *FDecl = (*Best)->Function;
10827 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010828 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10829 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010830 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010831 }
10832
Douglas Gregorb412e172010-07-25 18:17:45 +000010833 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010834 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010835}
10836
Sam Panzer0f384432012-08-21 00:52:01 +000010837/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10838/// (which eventually refers to the declaration Func) and the call
10839/// arguments Args/NumArgs, attempt to resolve the function call down
10840/// to a specific function. If overload resolution succeeds, returns
10841/// the call expression produced by overload resolution.
10842/// Otherwise, emits diagnostics and returns ExprError.
10843ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10844 UnresolvedLookupExpr *ULE,
10845 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010846 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010847 SourceLocation RParenLoc,
10848 Expr *ExecConfig,
10849 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000010850 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10851 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000010852 ExprResult result;
10853
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010854 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10855 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010856 return result;
10857
10858 OverloadCandidateSet::iterator Best;
10859 OverloadingResult OverloadResult =
10860 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10861
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010862 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010863 RParenLoc, ExecConfig, &CandidateSet,
10864 &Best, OverloadResult,
10865 AllowTypoCorrection);
10866}
10867
John McCall4c4c1df2010-01-26 03:27:55 +000010868static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010869 return Functions.size() > 1 ||
10870 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10871}
10872
Douglas Gregor084d8552009-03-13 23:49:33 +000010873/// \brief Create a unary operation that may resolve to an overloaded
10874/// operator.
10875///
10876/// \param OpLoc The location of the operator itself (e.g., '*').
10877///
10878/// \param OpcIn The UnaryOperator::Opcode that describes this
10879/// operator.
10880///
James Dennett18348b62012-06-22 08:52:37 +000010881/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010882/// considered by overload resolution. The caller needs to build this
10883/// set based on the context using, e.g.,
10884/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10885/// set should not contain any member functions; those will be added
10886/// by CreateOverloadedUnaryOp().
10887///
James Dennett91738ff2012-06-22 10:32:46 +000010888/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010889ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010890Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10891 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010892 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010893 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010894
10895 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10896 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10897 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010898 // TODO: provide better source location info.
10899 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010900
John McCall4124c492011-10-17 18:40:02 +000010901 if (checkPlaceholderForOverload(*this, Input))
10902 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010903
Craig Topperc3ec1492014-05-26 06:22:03 +000010904 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000010905 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010906
Douglas Gregor084d8552009-03-13 23:49:33 +000010907 // For post-increment and post-decrement, add the implicit '0' as
10908 // the second argument, so that we know this is a post-increment or
10909 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010910 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010911 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010912 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10913 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010914 NumArgs = 2;
10915 }
10916
Richard Smithe54c3072013-05-05 15:51:06 +000010917 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10918
Douglas Gregor084d8552009-03-13 23:49:33 +000010919 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010920 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010921 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10922 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010923
Craig Topperc3ec1492014-05-26 06:22:03 +000010924 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010925 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010926 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010927 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010928 /*ADL*/ true, IsOverloaded(Fns),
10929 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010930 return new (Context)
10931 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10932 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010933 }
10934
10935 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000010936 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000010937
10938 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010939 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010940
10941 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010942 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010943
John McCall4c4c1df2010-01-26 03:27:55 +000010944 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000010945 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000010946 /*ExplicitTemplateArgs*/nullptr,
10947 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000010948
Douglas Gregor084d8552009-03-13 23:49:33 +000010949 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010950 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010951
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010952 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10953
Douglas Gregor084d8552009-03-13 23:49:33 +000010954 // Perform overload resolution.
10955 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010956 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010957 case OR_Success: {
10958 // We found a built-in operator or an overloaded operator.
10959 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010960
Douglas Gregor084d8552009-03-13 23:49:33 +000010961 if (FnDecl) {
10962 // We matched an overloaded operator. Build a call to that
10963 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010964
Douglas Gregor084d8552009-03-13 23:49:33 +000010965 // Convert the arguments.
10966 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010967 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010968
John Wiegley01296292011-04-08 18:41:53 +000010969 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000010970 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000010971 Best->FoundDecl, Method);
10972 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010973 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010974 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010975 } else {
10976 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010977 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010978 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010979 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010980 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010981 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010982 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010983 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010984 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010985 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010986 }
10987
Douglas Gregor084d8552009-03-13 23:49:33 +000010988 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000010989 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010990 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010991 if (FnExpr.isInvalid())
10992 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010993
Richard Smithc1564702013-11-15 02:58:23 +000010994 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000010995 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000010996 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10997 ResultTy = ResultTy.getNonLValueExprType(Context);
10998
Eli Friedman030eee42009-11-18 03:58:17 +000010999 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011000 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011001 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011002 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011003
Alp Toker314cc812014-01-25 16:55:45 +000011004 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011005 return ExprError();
11006
John McCallb268a282010-08-23 23:25:46 +000011007 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011008 } else {
11009 // We matched a built-in operator. Convert the arguments, then
11010 // break out so that we will build the appropriate built-in
11011 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011012 ExprResult InputRes =
11013 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11014 Best->Conversions[0], AA_Passing);
11015 if (InputRes.isInvalid())
11016 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011017 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011018 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011019 }
John Wiegley01296292011-04-08 18:41:53 +000011020 }
11021
11022 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011023 // This is an erroneous use of an operator which can be overloaded by
11024 // a non-member function. Check for non-member operators which were
11025 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011026 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011027 // FIXME: Recover by calling the found function.
11028 return ExprError();
11029
John Wiegley01296292011-04-08 18:41:53 +000011030 // No viable function; fall through to handling this as a
11031 // built-in operator, which will produce an error message for us.
11032 break;
11033
11034 case OR_Ambiguous:
11035 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11036 << UnaryOperator::getOpcodeStr(Opc)
11037 << Input->getType()
11038 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011039 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011040 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11041 return ExprError();
11042
11043 case OR_Deleted:
11044 Diag(OpLoc, diag::err_ovl_deleted_oper)
11045 << Best->Function->isDeleted()
11046 << UnaryOperator::getOpcodeStr(Opc)
11047 << getDeletedOrUnavailableSuffix(Best->Function)
11048 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011049 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011050 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011051 return ExprError();
11052 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011053
11054 // Either we found no viable overloaded operator or we matched a
11055 // built-in operator. In either case, fall through to trying to
11056 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011057 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011058}
11059
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011060/// \brief Create a binary operation that may resolve to an overloaded
11061/// operator.
11062///
11063/// \param OpLoc The location of the operator itself (e.g., '+').
11064///
11065/// \param OpcIn The BinaryOperator::Opcode that describes this
11066/// operator.
11067///
James Dennett18348b62012-06-22 08:52:37 +000011068/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011069/// considered by overload resolution. The caller needs to build this
11070/// set based on the context using, e.g.,
11071/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11072/// set should not contain any member functions; those will be added
11073/// by CreateOverloadedBinOp().
11074///
11075/// \param LHS Left-hand argument.
11076/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011077ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011078Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000011079 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000011080 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011081 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011082 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011083 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011084
11085 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11086 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11087 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11088
11089 // If either side is type-dependent, create an appropriate dependent
11090 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011091 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011092 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011093 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011094 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011095 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011096 return new (Context) BinaryOperator(
11097 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11098 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011099
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011100 return new (Context) CompoundAssignOperator(
11101 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11102 Context.DependentTy, Context.DependentTy, OpLoc,
11103 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011104 }
John McCall4c4c1df2010-01-26 03:27:55 +000011105
11106 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011107 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011108 // TODO: provide better source location info in DNLoc component.
11109 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011110 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011111 = UnresolvedLookupExpr::Create(Context, NamingClass,
11112 NestedNameSpecifierLoc(), OpNameInfo,
11113 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011114 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011115 return new (Context)
11116 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11117 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011118 }
11119
John McCall4124c492011-10-17 18:40:02 +000011120 // Always do placeholder-like conversions on the RHS.
11121 if (checkPlaceholderForOverload(*this, Args[1]))
11122 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011123
John McCall526ab472011-10-25 17:37:35 +000011124 // Do placeholder-like conversion on the LHS; note that we should
11125 // not get here with a PseudoObject LHS.
11126 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011127 if (checkPlaceholderForOverload(*this, Args[0]))
11128 return ExprError();
11129
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011130 // If this is the assignment operator, we only perform overload resolution
11131 // if the left-hand side is a class or enumeration type. This is actually
11132 // a hack. The standard requires that we do overload resolution between the
11133 // various built-in candidates, but as DR507 points out, this can lead to
11134 // problems. So we do it this way, which pretty much follows what GCC does.
11135 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011136 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011137 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011138
John McCalle26a8722010-12-04 08:14:53 +000011139 // If this is the .* operator, which is not overloadable, just
11140 // create a built-in binary operator.
11141 if (Opc == BO_PtrMemD)
11142 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11143
Douglas Gregor084d8552009-03-13 23:49:33 +000011144 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011145 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011146
11147 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011148 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011149
11150 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011151 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011152
Richard Smith0daabd72014-09-23 20:31:39 +000011153 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11154 // performed for an assignment operator (nor for operator[] nor operator->,
11155 // which don't get here).
11156 if (Opc != BO_Assign)
11157 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11158 /*ExplicitTemplateArgs*/ nullptr,
11159 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011160
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011161 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011162 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011163
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011164 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11165
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011166 // Perform overload resolution.
11167 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011168 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011169 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011170 // We found a built-in operator or an overloaded operator.
11171 FunctionDecl *FnDecl = Best->Function;
11172
11173 if (FnDecl) {
11174 // We matched an overloaded operator. Build a call to that
11175 // operator.
11176
11177 // Convert the arguments.
11178 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011179 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011180 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011181
Chandler Carruth8e543b32010-12-12 08:17:55 +000011182 ExprResult Arg1 =
11183 PerformCopyInitialization(
11184 InitializedEntity::InitializeParameter(Context,
11185 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011186 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011187 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011188 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011189
John Wiegley01296292011-04-08 18:41:53 +000011190 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011191 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011192 Best->FoundDecl, Method);
11193 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011194 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011195 Args[0] = Arg0.getAs<Expr>();
11196 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011197 } else {
11198 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011199 ExprResult Arg0 = PerformCopyInitialization(
11200 InitializedEntity::InitializeParameter(Context,
11201 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011202 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011203 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011204 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011205
Chandler Carruth8e543b32010-12-12 08:17:55 +000011206 ExprResult Arg1 =
11207 PerformCopyInitialization(
11208 InitializedEntity::InitializeParameter(Context,
11209 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011210 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011211 if (Arg1.isInvalid())
11212 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011213 Args[0] = LHS = Arg0.getAs<Expr>();
11214 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011215 }
11216
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011217 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011218 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011219 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011220 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011221 if (FnExpr.isInvalid())
11222 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011223
Richard Smithc1564702013-11-15 02:58:23 +000011224 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011225 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011226 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11227 ResultTy = ResultTy.getNonLValueExprType(Context);
11228
John McCallb268a282010-08-23 23:25:46 +000011229 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011230 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011231 Args, ResultTy, VK, OpLoc,
11232 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011233
Alp Toker314cc812014-01-25 16:55:45 +000011234 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011235 FnDecl))
11236 return ExprError();
11237
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011238 ArrayRef<const Expr *> ArgsArray(Args, 2);
11239 // Cut off the implicit 'this'.
11240 if (isa<CXXMethodDecl>(FnDecl))
11241 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011242
11243 // Check for a self move.
11244 if (Op == OO_Equal)
11245 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11246
Douglas Gregorb4866e82015-06-19 18:13:19 +000011247 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011248 TheCall->getSourceRange(), VariadicDoesNotApply);
11249
John McCallb268a282010-08-23 23:25:46 +000011250 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011251 } else {
11252 // We matched a built-in operator. Convert the arguments, then
11253 // break out so that we will build the appropriate built-in
11254 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011255 ExprResult ArgsRes0 =
11256 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11257 Best->Conversions[0], AA_Passing);
11258 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011259 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011260 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011261
John Wiegley01296292011-04-08 18:41:53 +000011262 ExprResult ArgsRes1 =
11263 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11264 Best->Conversions[1], AA_Passing);
11265 if (ArgsRes1.isInvalid())
11266 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011267 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011268 break;
11269 }
11270 }
11271
Douglas Gregor66950a32009-09-30 21:46:01 +000011272 case OR_No_Viable_Function: {
11273 // C++ [over.match.oper]p9:
11274 // If the operator is the operator , [...] and there are no
11275 // viable functions, then the operator is assumed to be the
11276 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011277 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011278 break;
11279
Chandler Carruth8e543b32010-12-12 08:17:55 +000011280 // For class as left operand for assignment or compound assigment
11281 // operator do not fall through to handling in built-in, but report that
11282 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011283 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011284 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011285 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011286 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11287 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011288 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011289 if (Args[0]->getType()->isIncompleteType()) {
11290 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11291 << Args[0]->getType()
11292 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11293 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011294 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011295 // This is an erroneous use of an operator which can be overloaded by
11296 // a non-member function. Check for non-member operators which were
11297 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011298 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011299 // FIXME: Recover by calling the found function.
11300 return ExprError();
11301
Douglas Gregor66950a32009-09-30 21:46:01 +000011302 // No viable function; try to create a built-in operation, which will
11303 // produce an error. Then, show the non-viable candidates.
11304 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011305 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011306 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011307 "C++ binary operator overloading is missing candidates!");
11308 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011309 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011310 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011311 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011312 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011313
11314 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011315 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011316 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011317 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011318 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011319 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011320 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011321 return ExprError();
11322
11323 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011324 if (isImplicitlyDeleted(Best->Function)) {
11325 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11326 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011327 << Context.getRecordType(Method->getParent())
11328 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011329
Richard Smithde1a4872012-12-28 12:23:24 +000011330 // The user probably meant to call this special member. Just
11331 // explain why it's deleted.
11332 NoteDeletedFunction(Method);
11333 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011334 } else {
11335 Diag(OpLoc, diag::err_ovl_deleted_oper)
11336 << Best->Function->isDeleted()
11337 << BinaryOperator::getOpcodeStr(Opc)
11338 << getDeletedOrUnavailableSuffix(Best->Function)
11339 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11340 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011341 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011342 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011343 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011344 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011345
Douglas Gregor66950a32009-09-30 21:46:01 +000011346 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011347 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011348}
11349
John McCalldadc5752010-08-24 06:29:42 +000011350ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011351Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11352 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011353 Expr *Base, Expr *Idx) {
11354 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011355 DeclarationName OpName =
11356 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11357
11358 // If either side is type-dependent, create an appropriate dependent
11359 // expression.
11360 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11361
Craig Topperc3ec1492014-05-26 06:22:03 +000011362 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011363 // CHECKME: no 'operator' keyword?
11364 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11365 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011366 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011367 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011368 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011369 /*ADL*/ true, /*Overloaded*/ false,
11370 UnresolvedSetIterator(),
11371 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011372 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011373
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011374 return new (Context)
11375 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11376 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011377 }
11378
John McCall4124c492011-10-17 18:40:02 +000011379 // Handle placeholders on both operands.
11380 if (checkPlaceholderForOverload(*this, Args[0]))
11381 return ExprError();
11382 if (checkPlaceholderForOverload(*this, Args[1]))
11383 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011384
Sebastian Redladba46e2009-10-29 20:17:01 +000011385 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011386 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011387
11388 // Subscript can only be overloaded as a member function.
11389
11390 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011391 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011392
11393 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011394 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011395
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011396 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11397
Sebastian Redladba46e2009-10-29 20:17:01 +000011398 // Perform overload resolution.
11399 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011400 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011401 case OR_Success: {
11402 // We found a built-in operator or an overloaded operator.
11403 FunctionDecl *FnDecl = Best->Function;
11404
11405 if (FnDecl) {
11406 // We matched an overloaded operator. Build a call to that
11407 // operator.
11408
John McCalla0296f72010-03-19 07:35:19 +000011409 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011410
Sebastian Redladba46e2009-10-29 20:17:01 +000011411 // Convert the arguments.
11412 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011413 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011414 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011415 Best->FoundDecl, Method);
11416 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011417 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011418 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011419
Anders Carlssona68e51e2010-01-29 18:37:50 +000011420 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011421 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011422 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011423 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011424 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011425 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011426 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011427 if (InputInit.isInvalid())
11428 return ExprError();
11429
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011430 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011431
Sebastian Redladba46e2009-10-29 20:17:01 +000011432 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011433 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11434 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011435 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011436 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011437 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011438 OpLocInfo.getLoc(),
11439 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011440 if (FnExpr.isInvalid())
11441 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011442
Richard Smithc1564702013-11-15 02:58:23 +000011443 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011444 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011445 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11446 ResultTy = ResultTy.getNonLValueExprType(Context);
11447
John McCallb268a282010-08-23 23:25:46 +000011448 CXXOperatorCallExpr *TheCall =
11449 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011450 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011451 ResultTy, VK, RLoc,
11452 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011453
Alp Toker314cc812014-01-25 16:55:45 +000011454 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011455 return ExprError();
11456
John McCallb268a282010-08-23 23:25:46 +000011457 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011458 } else {
11459 // We matched a built-in operator. Convert the arguments, then
11460 // break out so that we will build the appropriate built-in
11461 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011462 ExprResult ArgsRes0 =
11463 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11464 Best->Conversions[0], AA_Passing);
11465 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011466 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011467 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011468
11469 ExprResult ArgsRes1 =
11470 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11471 Best->Conversions[1], AA_Passing);
11472 if (ArgsRes1.isInvalid())
11473 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011474 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011475
11476 break;
11477 }
11478 }
11479
11480 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011481 if (CandidateSet.empty())
11482 Diag(LLoc, diag::err_ovl_no_oper)
11483 << Args[0]->getType() << /*subscript*/ 0
11484 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11485 else
11486 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11487 << Args[0]->getType()
11488 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011489 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011490 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011491 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011492 }
11493
11494 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011495 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011496 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011497 << Args[0]->getType() << Args[1]->getType()
11498 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011499 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011500 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011501 return ExprError();
11502
11503 case OR_Deleted:
11504 Diag(LLoc, diag::err_ovl_deleted_oper)
11505 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011506 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011507 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011508 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011509 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011510 return ExprError();
11511 }
11512
11513 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011514 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011515}
11516
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011517/// BuildCallToMemberFunction - Build a call to a member
11518/// function. MemExpr is the expression that refers to the member
11519/// function (and includes the object parameter), Args/NumArgs are the
11520/// arguments to the function call (not including the object
11521/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011522/// expression refers to a non-static member function or an overloaded
11523/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011524ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011525Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011526 SourceLocation LParenLoc,
11527 MultiExprArg Args,
11528 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011529 assert(MemExprE->getType() == Context.BoundMemberTy ||
11530 MemExprE->getType() == Context.OverloadTy);
11531
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011532 // Dig out the member expression. This holds both the object
11533 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011534 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011535
John McCall0009fcc2011-04-26 20:42:42 +000011536 // Determine whether this is a call to a pointer-to-member function.
11537 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11538 assert(op->getType() == Context.BoundMemberTy);
11539 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11540
11541 QualType fnType =
11542 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11543
11544 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11545 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011546 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011547
11548 // Check that the object type isn't more qualified than the
11549 // member function we're calling.
11550 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11551
11552 QualType objectType = op->getLHS()->getType();
11553 if (op->getOpcode() == BO_PtrMemI)
11554 objectType = objectType->castAs<PointerType>()->getPointeeType();
11555 Qualifiers objectQuals = objectType.getQualifiers();
11556
11557 Qualifiers difference = objectQuals - funcQuals;
11558 difference.removeObjCGCAttr();
11559 difference.removeAddressSpace();
11560 if (difference) {
11561 std::string qualsString = difference.getAsString();
11562 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11563 << fnType.getUnqualifiedType()
11564 << qualsString
11565 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11566 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011567
David Majnemerb3e56542014-08-07 22:56:13 +000011568 if (resultType->isMemberPointerType())
11569 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11570 RequireCompleteType(LParenLoc, resultType, 0);
11571
John McCall0009fcc2011-04-26 20:42:42 +000011572 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011573 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011574 resultType, valueKind, RParenLoc);
11575
Alp Toker314cc812014-01-25 16:55:45 +000011576 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011577 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011578 return ExprError();
11579
Craig Topperc3ec1492014-05-26 06:22:03 +000011580 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011581 return ExprError();
11582
Richard Trieu9be9c682013-06-22 02:30:38 +000011583 if (CheckOtherCall(call, proto))
11584 return ExprError();
11585
John McCall0009fcc2011-04-26 20:42:42 +000011586 return MaybeBindToTemporary(call);
11587 }
11588
David Majnemerced8bdf2015-02-25 17:36:15 +000011589 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11590 return new (Context)
11591 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11592
John McCall4124c492011-10-17 18:40:02 +000011593 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011594 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011595 return ExprError();
11596
John McCall10eae182009-11-30 22:42:35 +000011597 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011598 CXXMethodDecl *Method = nullptr;
11599 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11600 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011601 if (isa<MemberExpr>(NakedMemExpr)) {
11602 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011603 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011604 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011605 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011606 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011607 } else {
11608 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011609 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011610
John McCall6e9f8f62009-12-03 04:06:58 +000011611 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011612 Expr::Classification ObjectClassification
11613 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11614 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011615
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011616 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011617 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11618 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011619
John McCall2d74de92009-12-01 22:10:20 +000011620 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011621 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011622 if (UnresExpr->hasExplicitTemplateArgs()) {
11623 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11624 TemplateArgs = &TemplateArgsBuffer;
11625 }
11626
John McCall10eae182009-11-30 22:42:35 +000011627 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11628 E = UnresExpr->decls_end(); I != E; ++I) {
11629
John McCall6e9f8f62009-12-03 04:06:58 +000011630 NamedDecl *Func = *I;
11631 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11632 if (isa<UsingShadowDecl>(Func))
11633 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11634
Douglas Gregor02824322011-01-26 19:30:28 +000011635
Francois Pichet64225792011-01-18 05:04:39 +000011636 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011637 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011638 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011639 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011640 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011641 // If explicit template arguments were provided, we can't call a
11642 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011643 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011644 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011645
John McCalla0296f72010-03-19 07:35:19 +000011646 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011647 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011648 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011649 } else {
John McCall10eae182009-11-30 22:42:35 +000011650 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011651 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011652 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011653 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011654 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011655 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011656 }
Mike Stump11289f42009-09-09 15:08:12 +000011657
John McCall10eae182009-11-30 22:42:35 +000011658 DeclarationName DeclName = UnresExpr->getMemberName();
11659
John McCall4124c492011-10-17 18:40:02 +000011660 UnbridgedCasts.restore();
11661
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011662 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011663 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011664 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011665 case OR_Success:
11666 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011667 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011668 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011669 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11670 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011671 // If FoundDecl is different from Method (such as if one is a template
11672 // and the other a specialization), make sure DiagnoseUseOfDecl is
11673 // called on both.
11674 // FIXME: This would be more comprehensively addressed by modifying
11675 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11676 // being used.
11677 if (Method != FoundDecl.getDecl() &&
11678 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11679 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011680 break;
11681
11682 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011683 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011684 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011685 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011686 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011687 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011688 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011689
11690 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011691 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011692 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011693 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011694 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011695 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011696
11697 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011698 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011699 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011700 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011701 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011702 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011703 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011704 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011705 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011706 }
11707
John McCall16df1e52010-03-30 21:47:33 +000011708 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011709
John McCall2d74de92009-12-01 22:10:20 +000011710 // If overload resolution picked a static member, build a
11711 // non-member call based on that function.
11712 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011713 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11714 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011715 }
11716
John McCall10eae182009-11-30 22:42:35 +000011717 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011718 }
11719
Alp Toker314cc812014-01-25 16:55:45 +000011720 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011721 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11722 ResultType = ResultType.getNonLValueExprType(Context);
11723
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011724 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011725 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011726 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011727 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011728
Eli Bendersky291a57e2014-09-25 23:59:08 +000011729 // (CUDA B.1): Check for invalid calls between targets.
11730 if (getLangOpts().CUDA) {
11731 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11732 if (CheckCUDATarget(Caller, Method)) {
11733 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11734 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11735 << IdentifyCUDATarget(Caller);
11736 return ExprError();
11737 }
11738 }
11739 }
11740
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011741 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000011742 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011743 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011744 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011745
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011746 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011747 // We only need to do this if there was actually an overload; otherwise
11748 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011749 if (!Method->isStatic()) {
11750 ExprResult ObjectArg =
11751 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11752 FoundDecl, Method);
11753 if (ObjectArg.isInvalid())
11754 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011755 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000011756 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011757
11758 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011759 const FunctionProtoType *Proto =
11760 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011761 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011762 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011763 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011764
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011765 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011766
Richard Smith55ce3522012-06-25 20:30:08 +000011767 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011768 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011769
Anders Carlsson47061ee2011-05-06 14:25:31 +000011770 if ((isa<CXXConstructorDecl>(CurContext) ||
11771 isa<CXXDestructorDecl>(CurContext)) &&
11772 TheCall->getMethodDecl()->isPure()) {
11773 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11774
Davide Italianoccb37382015-07-14 23:36:10 +000011775 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
11776 MemExpr->performsVirtualDispatch(getLangOpts())) {
11777 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000011778 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11779 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11780 << MD->getParent()->getDeclName();
11781
11782 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000011783 if (getLangOpts().AppleKext)
11784 Diag(MemExpr->getLocStart(),
11785 diag::note_pure_qualified_call_kext)
11786 << MD->getParent()->getDeclName()
11787 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011788 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011789 }
John McCallb268a282010-08-23 23:25:46 +000011790 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011791}
11792
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011793/// BuildCallToObjectOfClassType - Build a call to an object of class
11794/// type (C++ [over.call.object]), which can end up invoking an
11795/// overloaded function call operator (@c operator()) or performing a
11796/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011797ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011798Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011799 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011800 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011801 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011802 if (checkPlaceholderForOverload(*this, Obj))
11803 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011804 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000011805
11806 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011807 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011808 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011809
Nico Weberb58e51c2014-11-19 05:21:39 +000011810 assert(Object.get()->getType()->isRecordType() &&
11811 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000011812 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011813
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011814 // C++ [over.call.object]p1:
11815 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011816 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011817 // candidate functions includes at least the function call
11818 // operators of T. The function call operators of T are obtained by
11819 // ordinary lookup of the name operator() in the context of
11820 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000011821 OverloadCandidateSet CandidateSet(LParenLoc,
11822 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000011823 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011824
John Wiegley01296292011-04-08 18:41:53 +000011825 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011826 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011827 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011828
John McCall27b18f82009-11-17 02:14:36 +000011829 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11830 LookupQualifiedName(R, Record->getDecl());
11831 R.suppressDiagnostics();
11832
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011833 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011834 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011835 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011836 Object.get()->Classify(Context),
11837 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011838 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011839 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011840
Douglas Gregorab7897a2008-11-19 22:57:39 +000011841 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011842 // In addition, for each (non-explicit in C++0x) conversion function
11843 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011844 //
11845 // operator conversion-type-id () cv-qualifier;
11846 //
11847 // where cv-qualifier is the same cv-qualification as, or a
11848 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011849 // denotes the type "pointer to function of (P1,...,Pn) returning
11850 // R", or the type "reference to pointer to function of
11851 // (P1,...,Pn) returning R", or the type "reference to function
11852 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011853 // is also considered as a candidate function. Similarly,
11854 // surrogate call functions are added to the set of candidate
11855 // functions for each conversion function declared in an
11856 // accessible base class provided the function is not hidden
11857 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000011858 const auto &Conversions =
11859 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11860 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011861 NamedDecl *D = *I;
11862 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11863 if (isa<UsingShadowDecl>(D))
11864 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011865
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011866 // Skip over templated conversion functions; they aren't
11867 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011868 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011869 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011870
John McCall6e9f8f62009-12-03 04:06:58 +000011871 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011872 if (!Conv->isExplicit()) {
11873 // Strip the reference type (if any) and then the pointer type (if
11874 // any) to get down to what might be a function type.
11875 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11876 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11877 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011878
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011879 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11880 {
11881 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011882 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011883 }
11884 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011885 }
Mike Stump11289f42009-09-09 15:08:12 +000011886
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011887 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11888
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011889 // Perform overload resolution.
11890 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011891 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011892 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011893 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011894 // Overload resolution succeeded; we'll build the appropriate call
11895 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011896 break;
11897
11898 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011899 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011900 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011901 << Object.get()->getType() << /*call*/ 1
11902 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011903 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011904 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011905 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011906 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011907 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011908 break;
11909
11910 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011911 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011912 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011913 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011914 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011915 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011916
11917 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011918 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011919 diag::err_ovl_deleted_object_call)
11920 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011921 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011922 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011923 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011924 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011925 break;
Mike Stump11289f42009-09-09 15:08:12 +000011926 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011927
Douglas Gregorb412e172010-07-25 18:17:45 +000011928 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011929 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011930
John McCall4124c492011-10-17 18:40:02 +000011931 UnbridgedCasts.restore();
11932
Craig Topperc3ec1492014-05-26 06:22:03 +000011933 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000011934 // Since there is no function declaration, this is one of the
11935 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011936 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011937 = cast<CXXConversionDecl>(
11938 Best->Conversions[0].UserDefined.ConversionFunction);
11939
Craig Topperc3ec1492014-05-26 06:22:03 +000011940 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11941 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011942 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11943 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011944 assert(Conv == Best->FoundDecl.getDecl() &&
11945 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011946 // We selected one of the surrogate functions that converts the
11947 // object parameter to a function pointer. Perform the conversion
11948 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011949
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011950 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011951 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011952 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11953 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011954 if (Call.isInvalid())
11955 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011956 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011957 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11958 CK_UserDefinedConversion, Call.get(),
11959 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011960
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011961 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011962 }
11963
Craig Topperc3ec1492014-05-26 06:22:03 +000011964 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011965
Douglas Gregorab7897a2008-11-19 22:57:39 +000011966 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11967 // that calls this method, using Object for the implicit object
11968 // parameter and passing along the remaining arguments.
11969 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011970
11971 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011972 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011973 return ExprError();
11974
Chandler Carruth8e543b32010-12-12 08:17:55 +000011975 const FunctionProtoType *Proto =
11976 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011977
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011978 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000011979
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011980 DeclarationNameInfo OpLocInfo(
11981 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11982 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011983 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011984 HadMultipleCandidates,
11985 OpLocInfo.getLoc(),
11986 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011987 if (NewFn.isInvalid())
11988 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011989
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011990 // Build the full argument list for the method call (the implicit object
11991 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000011992 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011993 MethodArgs[0] = Object.get();
11994 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11995
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011996 // Once we've built TheCall, all of the expressions are properly
11997 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000011998 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011999 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12000 ResultTy = ResultTy.getNonLValueExprType(Context);
12001
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012002 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012003 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012004 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12005 ResultTy, VK, RParenLoc, false);
12006 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012007
Alp Toker314cc812014-01-25 16:55:45 +000012008 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012009 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012010
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012011 // We may have default arguments. If so, we need to allocate more
12012 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012013 if (Args.size() < NumParams)
12014 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012015
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012016 bool IsError = false;
12017
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012018 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012019 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012020 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012021 Best->FoundDecl, Method);
12022 if (ObjRes.isInvalid())
12023 IsError = true;
12024 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012025 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012026 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012027
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012028 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012029 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012030 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012031 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012032 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012033
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012034 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012035
John McCalldadc5752010-08-24 06:29:42 +000012036 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012037 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012038 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012039 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012040 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012041
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012042 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012043 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012044 } else {
John McCalldadc5752010-08-24 06:29:42 +000012045 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012046 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12047 if (DefArg.isInvalid()) {
12048 IsError = true;
12049 break;
12050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012051
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012052 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012053 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012054
12055 TheCall->setArg(i + 1, Arg);
12056 }
12057
12058 // If this is a variadic call, handle args passed through "...".
12059 if (Proto->isVariadic()) {
12060 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012061 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012062 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12063 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012064 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012065 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012066 }
12067 }
12068
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012069 if (IsError) return true;
12070
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012071 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012072
Richard Smith55ce3522012-06-25 20:30:08 +000012073 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012074 return true;
12075
John McCalle172be52010-08-24 06:09:16 +000012076 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012077}
12078
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012079/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012080/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012081/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012082ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012083Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12084 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012085 assert(Base->getType()->isRecordType() &&
12086 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012087
John McCall4124c492011-10-17 18:40:02 +000012088 if (checkPlaceholderForOverload(*this, Base))
12089 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012090
John McCallbc077cf2010-02-08 23:07:23 +000012091 SourceLocation Loc = Base->getExprLoc();
12092
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012093 // C++ [over.ref]p1:
12094 //
12095 // [...] An expression x->m is interpreted as (x.operator->())->m
12096 // for a class object x of type T if T::operator->() exists and if
12097 // the operator is selected as the best match function by the
12098 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012099 DeclarationName OpName =
12100 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012101 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012102 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012103
John McCallbc077cf2010-02-08 23:07:23 +000012104 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012105 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012106 return ExprError();
12107
John McCall27b18f82009-11-17 02:14:36 +000012108 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12109 LookupQualifiedName(R, BaseRecord->getDecl());
12110 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012111
12112 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012113 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012114 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012115 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012116 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012117
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012118 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12119
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012120 // Perform overload resolution.
12121 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012122 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012123 case OR_Success:
12124 // Overload resolution succeeded; we'll build the call below.
12125 break;
12126
12127 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012128 if (CandidateSet.empty()) {
12129 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012130 if (NoArrowOperatorFound) {
12131 // Report this specific error to the caller instead of emitting a
12132 // diagnostic, as requested.
12133 *NoArrowOperatorFound = true;
12134 return ExprError();
12135 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012136 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12137 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012138 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012139 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012140 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012141 }
12142 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012143 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012144 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012145 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012146 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012147
12148 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012149 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12150 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012151 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012152 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012153
12154 case OR_Deleted:
12155 Diag(OpLoc, diag::err_ovl_deleted_oper)
12156 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012157 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012158 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012159 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012160 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012161 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012162 }
12163
Craig Topperc3ec1492014-05-26 06:22:03 +000012164 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012165
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012166 // Convert the object parameter.
12167 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012168 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012169 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012170 Best->FoundDecl, Method);
12171 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012172 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012173 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012174
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012175 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012176 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012177 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012178 if (FnExpr.isInvalid())
12179 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012180
Alp Toker314cc812014-01-25 16:55:45 +000012181 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012182 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12183 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012184 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012185 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012186 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012187
Alp Toker314cc812014-01-25 16:55:45 +000012188 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012189 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012190
12191 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012192}
12193
Richard Smithbcc22fc2012-03-09 08:00:36 +000012194/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12195/// a literal operator described by the provided lookup results.
12196ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12197 DeclarationNameInfo &SuffixInfo,
12198 ArrayRef<Expr*> Args,
12199 SourceLocation LitEndLoc,
12200 TemplateArgumentListInfo *TemplateArgs) {
12201 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012202
Richard Smith100b24a2014-04-17 01:52:14 +000012203 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12204 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012205 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12206 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012207
Richard Smithbcc22fc2012-03-09 08:00:36 +000012208 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12209
Richard Smithbcc22fc2012-03-09 08:00:36 +000012210 // Perform overload resolution. This will usually be trivial, but might need
12211 // to perform substitutions for a literal operator template.
12212 OverloadCandidateSet::iterator Best;
12213 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12214 case OR_Success:
12215 case OR_Deleted:
12216 break;
12217
12218 case OR_No_Viable_Function:
12219 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12220 << R.getLookupName();
12221 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12222 return ExprError();
12223
12224 case OR_Ambiguous:
12225 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12226 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12227 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012228 }
12229
Richard Smithbcc22fc2012-03-09 08:00:36 +000012230 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012231 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12232 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012233 SuffixInfo.getLoc(),
12234 SuffixInfo.getInfo());
12235 if (Fn.isInvalid())
12236 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012237
12238 // Check the argument types. This should almost always be a no-op, except
12239 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012240 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012241 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012242 ExprResult InputInit = PerformCopyInitialization(
12243 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12244 SourceLocation(), Args[ArgIdx]);
12245 if (InputInit.isInvalid())
12246 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012247 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012248 }
12249
Alp Toker314cc812014-01-25 16:55:45 +000012250 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012251 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12252 ResultTy = ResultTy.getNonLValueExprType(Context);
12253
Richard Smithc67fdd42012-03-07 08:35:16 +000012254 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012255 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012256 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012257 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12258
Alp Toker314cc812014-01-25 16:55:45 +000012259 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012260 return ExprError();
12261
Craig Topperc3ec1492014-05-26 06:22:03 +000012262 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012263 return ExprError();
12264
12265 return MaybeBindToTemporary(UDL);
12266}
12267
Sam Panzer0f384432012-08-21 00:52:01 +000012268/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12269/// given LookupResult is non-empty, it is assumed to describe a member which
12270/// will be invoked. Otherwise, the function will be found via argument
12271/// dependent lookup.
12272/// CallExpr is set to a valid expression and FRS_Success returned on success,
12273/// otherwise CallExpr is set to ExprError() and some non-success value
12274/// is returned.
12275Sema::ForRangeStatus
12276Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12277 SourceLocation RangeLoc, VarDecl *Decl,
12278 BeginEndFunction BEF,
12279 const DeclarationNameInfo &NameInfo,
12280 LookupResult &MemberLookup,
12281 OverloadCandidateSet *CandidateSet,
12282 Expr *Range, ExprResult *CallExpr) {
12283 CandidateSet->clear();
12284 if (!MemberLookup.empty()) {
12285 ExprResult MemberRef =
12286 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12287 /*IsPtr=*/false, CXXScopeSpec(),
12288 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012289 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012290 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +000012291 /*TemplateArgs=*/nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012292 if (MemberRef.isInvalid()) {
12293 *CallExpr = ExprError();
12294 Diag(Range->getLocStart(), diag::note_in_for_range)
12295 << RangeLoc << BEF << Range->getType();
12296 return FRS_DiagnosticIssued;
12297 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012298 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012299 if (CallExpr->isInvalid()) {
12300 *CallExpr = ExprError();
12301 Diag(Range->getLocStart(), diag::note_in_for_range)
12302 << RangeLoc << BEF << Range->getType();
12303 return FRS_DiagnosticIssued;
12304 }
12305 } else {
12306 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012307 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012308 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012309 NestedNameSpecifierLoc(), NameInfo,
12310 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012311 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012312
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012313 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012314 CandidateSet, CallExpr);
12315 if (CandidateSet->empty() || CandidateSetError) {
12316 *CallExpr = ExprError();
12317 return FRS_NoViableFunction;
12318 }
12319 OverloadCandidateSet::iterator Best;
12320 OverloadingResult OverloadResult =
12321 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12322
12323 if (OverloadResult == OR_No_Viable_Function) {
12324 *CallExpr = ExprError();
12325 return FRS_NoViableFunction;
12326 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012327 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012328 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012329 OverloadResult,
12330 /*AllowTypoCorrection=*/false);
12331 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12332 *CallExpr = ExprError();
12333 Diag(Range->getLocStart(), diag::note_in_for_range)
12334 << RangeLoc << BEF << Range->getType();
12335 return FRS_DiagnosticIssued;
12336 }
12337 }
12338 return FRS_Success;
12339}
12340
12341
Douglas Gregorcd695e52008-11-10 20:40:00 +000012342/// FixOverloadedFunctionReference - E is an expression that refers to
12343/// a C++ overloaded function (possibly with some parentheses and
12344/// perhaps a '&' around it). We have resolved the overloaded function
12345/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012346/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012347Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012348 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012349 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012350 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12351 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012352 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012353 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012354
Douglas Gregor51c538b2009-11-20 19:42:02 +000012355 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012356 }
12357
Douglas Gregor51c538b2009-11-20 19:42:02 +000012358 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012359 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12360 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012361 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012362 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012363 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012364 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012365 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012366 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012367
12368 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012369 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012370 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012371 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012372 }
12373
Douglas Gregor51c538b2009-11-20 19:42:02 +000012374 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012375 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012376 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012377 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12378 if (Method->isStatic()) {
12379 // Do nothing: static member functions aren't any different
12380 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012381 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012382 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012383 // UnresolvedLookupExpr holding an overloaded member function
12384 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012385 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12386 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012387 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012388 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012389
John McCalld14a8642009-11-21 08:51:07 +000012390 assert(isa<DeclRefExpr>(SubExpr)
12391 && "fixed to something other than a decl ref");
12392 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12393 && "fixed to a member ref with no nested name qualifier");
12394
12395 // We have taken the address of a pointer to member
12396 // function. Perform the computation here so that we get the
12397 // appropriate pointer to member type.
12398 QualType ClassType
12399 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12400 QualType MemPtrType
12401 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12402
John McCall7decc9e2010-11-18 06:31:45 +000012403 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12404 VK_RValue, OK_Ordinary,
12405 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012406 }
12407 }
John McCall16df1e52010-03-30 21:47:33 +000012408 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12409 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012410 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012411 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012412
John McCalle3027922010-08-25 11:45:40 +000012413 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012414 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012415 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012416 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012417 }
John McCalld14a8642009-11-21 08:51:07 +000012418
12419 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012420 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012421 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012422 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012423 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12424 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012425 }
12426
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012427 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12428 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012429 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012430 Fn,
John McCall113bee02012-03-10 09:33:50 +000012431 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012432 ULE->getNameLoc(),
12433 Fn->getType(),
12434 VK_LValue,
12435 Found.getDecl(),
12436 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012437 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012438 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12439 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012440 }
12441
John McCall10eae182009-11-30 22:42:35 +000012442 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012443 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012444 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012445 if (MemExpr->hasExplicitTemplateArgs()) {
12446 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12447 TemplateArgs = &TemplateArgsBuffer;
12448 }
John McCall6b51f282009-11-23 01:53:49 +000012449
John McCall2d74de92009-12-01 22:10:20 +000012450 Expr *Base;
12451
John McCall7decc9e2010-11-18 06:31:45 +000012452 // If we're filling in a static method where we used to have an
12453 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012454 if (MemExpr->isImplicitAccess()) {
12455 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012456 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12457 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012458 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012459 Fn,
John McCall113bee02012-03-10 09:33:50 +000012460 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012461 MemExpr->getMemberLoc(),
12462 Fn->getType(),
12463 VK_LValue,
12464 Found.getDecl(),
12465 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012466 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012467 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12468 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012469 } else {
12470 SourceLocation Loc = MemExpr->getMemberLoc();
12471 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012472 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012473 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012474 Base = new (Context) CXXThisExpr(Loc,
12475 MemExpr->getBaseType(),
12476 /*isImplicit=*/true);
12477 }
John McCall2d74de92009-12-01 22:10:20 +000012478 } else
John McCallc3007a22010-10-26 07:05:15 +000012479 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012480
John McCall4adb38c2011-04-27 00:36:17 +000012481 ExprValueKind valueKind;
12482 QualType type;
12483 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12484 valueKind = VK_LValue;
12485 type = Fn->getType();
12486 } else {
12487 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000012488 type = Context.BoundMemberTy;
12489 }
12490
12491 MemberExpr *ME = MemberExpr::Create(
12492 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12493 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12494 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12495 OK_Ordinary);
12496 ME->setHadMultipleCandidates(true);
12497 MarkMemberReferenced(ME);
12498 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012500
John McCallc3007a22010-10-26 07:05:15 +000012501 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012502}
12503
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012504ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012505 DeclAccessPair Found,
12506 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012507 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012508}