blob: d364f8d11549a6341e41ef29c5616cfa8ae86bd3 [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) {
289 // -- from a floating-point type to an integer type, or
290 //
291 // -- from an integer type or unscoped enumeration type to a floating-point
292 // type, except where the source is a constant expression and the actual
293 // value after conversion will fit into the target type and will produce
294 // the original value when converted back to the original type, or
295 case ICK_Floating_Integral:
296 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
297 return NK_Type_Narrowing;
298 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
299 llvm::APSInt IntConstantValue;
300 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
301 if (Initializer &&
302 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
303 // Convert the integer to the floating type.
304 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
305 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
306 llvm::APFloat::rmNearestTiesToEven);
307 // And back.
308 llvm::APSInt ConvertedValue = IntConstantValue;
309 bool ignored;
310 Result.convertToInteger(ConvertedValue,
311 llvm::APFloat::rmTowardZero, &ignored);
312 // If the resulting value is different, this was a narrowing conversion.
313 if (IntConstantValue != ConvertedValue) {
314 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000315 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000316 return NK_Constant_Narrowing;
317 }
318 } else {
319 // Variables are always narrowings.
320 return NK_Variable_Narrowing;
321 }
322 }
323 return NK_Not_Narrowing;
324
325 // -- from long double to double or float, or from double to float, except
326 // where the source is a constant expression and the actual value after
327 // conversion is within the range of values that can be represented (even
328 // if it cannot be represented exactly), or
329 case ICK_Floating_Conversion:
330 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
331 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
332 // FromType is larger than ToType.
333 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
335 // Constant!
336 assert(ConstantValue.isFloat());
337 llvm::APFloat FloatVal = ConstantValue.getFloat();
338 // Convert the source value into the target type.
339 bool ignored;
340 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
341 Ctx.getFloatTypeSemantics(ToType),
342 llvm::APFloat::rmNearestTiesToEven, &ignored);
343 // If there was no overflow, the source value is within the range of
344 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000345 if (ConvertStatus & llvm::APFloat::opOverflow) {
346 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000347 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000348 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000349 } else {
350 return NK_Variable_Narrowing;
351 }
352 }
353 return NK_Not_Narrowing;
354
355 // -- from an integer type or unscoped enumeration type to an integer type
356 // that cannot represent all the values of the original type, except where
357 // the source is a constant expression and the actual value after
358 // conversion will fit into the target type and will produce the original
359 // value when converted back to the original type.
360 case ICK_Boolean_Conversion: // Bools are integers too.
361 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
362 // Boolean conversions can be from pointers and pointers to members
363 // [conv.bool], and those aren't considered narrowing conversions.
364 return NK_Not_Narrowing;
365 } // Otherwise, fall through to the integral case.
366 case ICK_Integral_Conversion: {
367 assert(FromType->isIntegralOrUnscopedEnumerationType());
368 assert(ToType->isIntegralOrUnscopedEnumerationType());
369 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
370 const unsigned FromWidth = Ctx.getIntWidth(FromType);
371 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
372 const unsigned ToWidth = Ctx.getIntWidth(ToType);
373
374 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000375 (FromWidth == ToWidth && FromSigned != ToSigned) ||
376 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000377 // Not all values of FromType can be represented in ToType.
378 llvm::APSInt InitializerValue;
379 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000380 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
381 // Such conversions on variables are always narrowing.
382 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000383 }
384 bool Narrowing = false;
385 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000386 // Negative -> unsigned is narrowing. Otherwise, more bits is never
387 // narrowing.
388 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000389 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000390 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000391 // Add a bit to the InitializerValue so we don't have to worry about
392 // signed vs. unsigned comparisons.
393 InitializerValue = InitializerValue.extend(
394 InitializerValue.getBitWidth() + 1);
395 // Convert the initializer to and from the target width and signed-ness.
396 llvm::APSInt ConvertedValue = InitializerValue;
397 ConvertedValue = ConvertedValue.trunc(ToWidth);
398 ConvertedValue.setIsSigned(ToSigned);
399 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
400 ConvertedValue.setIsSigned(InitializerValue.isSigned());
401 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000402 if (ConvertedValue != InitializerValue)
403 Narrowing = true;
404 }
405 if (Narrowing) {
406 ConstantType = Initializer->getType();
407 ConstantValue = APValue(InitializerValue);
408 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000409 }
410 }
411 return NK_Not_Narrowing;
412 }
413
414 default:
415 // Other kinds of conversions are not narrowings.
416 return NK_Not_Narrowing;
417 }
418}
419
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000420/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000421/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000422void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000423 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000424 bool PrintedSomething = false;
425 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000426 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000427 PrintedSomething = true;
428 }
429
430 if (Second != ICK_Identity) {
431 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000432 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000433 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000434 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000435
436 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000437 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000438 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000439 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000440 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000441 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000442 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000443 PrintedSomething = true;
444 }
445
446 if (Third != ICK_Identity) {
447 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000448 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000449 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000450 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000451 PrintedSomething = true;
452 }
453
454 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000455 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000456 }
457}
458
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000459/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000460/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000461void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000462 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000463 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000464 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000465 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000467 if (ConversionFunction)
468 OS << '\'' << *ConversionFunction << '\'';
469 else
470 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000471 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000473 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474 }
475}
476
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000477/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000478/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000479void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000480 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000481 if (isStdInitializerListElement())
482 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483 switch (ConversionKind) {
484 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000485 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000486 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 break;
488 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000489 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000490 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 break;
492 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000493 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000494 break;
John McCall0d1da222010-01-12 00:44:57 +0000495 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000496 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000497 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 break;
501 }
502
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000503 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504}
505
John McCall0d1da222010-01-12 00:44:57 +0000506void AmbiguousConversionSequence::construct() {
507 new (&conversions()) ConversionSet();
508}
509
510void AmbiguousConversionSequence::destruct() {
511 conversions().~ConversionSet();
512}
513
514void
515AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
516 FromTypePtr = O.FromTypePtr;
517 ToTypePtr = O.ToTypePtr;
518 new (&conversions()) ConversionSet(O.conversions());
519}
520
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000521namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000522 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000523 // template argument information.
524 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000525 TemplateArgument FirstArg;
526 TemplateArgument SecondArg;
527 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000528 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000529 // template parameter and template argument information.
530 struct DFIParamWithArguments : DFIArguments {
531 TemplateParameter Param;
532 };
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000533}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000534
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000535/// \brief Convert from Sema's representation of template deduction information
536/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000537DeductionFailureInfo
538clang::MakeDeductionFailureInfo(ASTContext &Context,
539 Sema::TemplateDeductionResult TDK,
540 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000541 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000542 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000543 Result.HasDiagnostic = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000544 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000545 switch (TDK) {
546 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000547 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000548 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000549 case Sema::TDK_TooManyArguments:
550 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000551 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000552
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000553 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000554 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000555 Result.Data = Info.Param.getOpaqueValue();
556 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557
Richard Smith44ecdbd2013-01-31 05:19:49 +0000558 case Sema::TDK_NonDeducedMismatch: {
559 // FIXME: Should allocate from normal heap so that we can free this later.
560 DFIArguments *Saved = new (Context) DFIArguments;
561 Saved->FirstArg = Info.FirstArg;
562 Saved->SecondArg = Info.SecondArg;
563 Result.Data = Saved;
564 break;
565 }
566
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000568 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000569 // FIXME: Should allocate from normal heap so that we can free this later.
570 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000571 Saved->Param = Info.Param;
572 Saved->FirstArg = Info.FirstArg;
573 Saved->SecondArg = Info.SecondArg;
574 Result.Data = Saved;
575 break;
576 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000577
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000578 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000579 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000580 if (Info.hasSFINAEDiagnostic()) {
581 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
582 SourceLocation(), PartialDiagnostic::NullDiagnostic());
583 Info.takeSFINAEDiagnostic(*Diag);
584 Result.HasDiagnostic = true;
585 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000586 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000588 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000589 Result.Data = Info.Expression;
590 break;
591
Richard Smith44ecdbd2013-01-31 05:19:49 +0000592 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000596 return Result;
597}
John McCall0d1da222010-01-12 00:44:57 +0000598
Larisse Voufo98b20f12013-07-19 23:00:19 +0000599void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
601 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000602 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 case Sema::TDK_InstantiationDepth:
604 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000605 case Sema::TDK_TooManyArguments:
606 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000607 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000608 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000611 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000612 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000613 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000614 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000615 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000616 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000617
618 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000619 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000620 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000621 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
622 Diag->~PartialDiagnosticAt();
623 HasDiagnostic = false;
624 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000625 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Douglas Gregor461761d2010-05-08 18:20:53 +0000627 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000628 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000629 break;
630 }
631}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632
Larisse Voufo98b20f12013-07-19 23:00:19 +0000633PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000634 if (HasDiagnostic)
635 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000636 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000637}
638
Larisse Voufo98b20f12013-07-19 23:00:19 +0000639TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000640 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
641 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000642 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000643 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000644 case Sema::TDK_TooManyArguments:
645 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000646 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000647 case Sema::TDK_NonDeducedMismatch:
648 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000649 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000650
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000651 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000652 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000654
655 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000656 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000657 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000659 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000660 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 break;
662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000664 return TemplateParameter();
665}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666
Larisse Voufo98b20f12013-07-19 23:00:19 +0000667TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000668 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000669 case Sema::TDK_Success:
670 case Sema::TDK_Invalid:
671 case Sema::TDK_InstantiationDepth:
672 case Sema::TDK_TooManyArguments:
673 case Sema::TDK_TooFewArguments:
674 case Sema::TDK_Incomplete:
675 case Sema::TDK_InvalidExplicitArguments:
676 case Sema::TDK_Inconsistent:
677 case Sema::TDK_Underqualified:
678 case Sema::TDK_NonDeducedMismatch:
679 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000680 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000681
Richard Smith44ecdbd2013-01-31 05:19:49 +0000682 case Sema::TDK_SubstitutionFailure:
683 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000684
Richard Smith44ecdbd2013-01-31 05:19:49 +0000685 // Unhandled
686 case Sema::TDK_MiscellaneousDeductionFailure:
687 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000688 }
689
Craig Topperc3ec1492014-05-26 06:22:03 +0000690 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000691}
692
Larisse Voufo98b20f12013-07-19 23:00:19 +0000693const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000696 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 case Sema::TDK_InstantiationDepth:
698 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000699 case Sema::TDK_TooManyArguments:
700 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000701 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000702 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000703 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000704 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000705
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000706 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000707 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000708 case Sema::TDK_NonDeducedMismatch:
709 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000710
Douglas Gregor461761d2010-05-08 18:20:53 +0000711 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000712 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000713 break;
714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000715
Craig Topperc3ec1492014-05-26 06:22:03 +0000716 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000718
Larisse Voufo98b20f12013-07-19 23:00:19 +0000719const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000720 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
721 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000722 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000723 case Sema::TDK_InstantiationDepth:
724 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000725 case Sema::TDK_TooManyArguments:
726 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000727 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000728 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000729 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000730 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000732 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000733 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000734 case Sema::TDK_NonDeducedMismatch:
735 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736
Douglas Gregor461761d2010-05-08 18:20:53 +0000737 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000738 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000739 break;
740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000741
Craig Topperc3ec1492014-05-26 06:22:03 +0000742 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000743}
744
Larisse Voufo98b20f12013-07-19 23:00:19 +0000745Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000746 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
747 Sema::TDK_FailedOverloadResolution)
748 return static_cast<Expr*>(Data);
749
Craig Topperc3ec1492014-05-26 06:22:03 +0000750 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000751}
752
Benjamin Kramer97e59492012-10-09 15:52:25 +0000753void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000754 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000755 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
756 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000757 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
758 i->DeductionFailure.Destroy();
759 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000760}
761
762void OverloadCandidateSet::clear() {
763 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000764 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000765 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000766 Functions.clear();
767}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000768
John McCall4124c492011-10-17 18:40:02 +0000769namespace {
770 class UnbridgedCastsSet {
771 struct Entry {
772 Expr **Addr;
773 Expr *Saved;
774 };
775 SmallVector<Entry, 2> Entries;
776
777 public:
778 void save(Sema &S, Expr *&E) {
779 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
780 Entry entry = { &E, E };
781 Entries.push_back(entry);
782 E = S.stripARCUnbridgedCast(E);
783 }
784
785 void restore() {
786 for (SmallVectorImpl<Entry>::iterator
787 i = Entries.begin(), e = Entries.end(); i != e; ++i)
788 *i->Addr = i->Saved;
789 }
790 };
791}
792
793/// checkPlaceholderForOverload - Do any interesting placeholder-like
794/// preprocessing on the given expression.
795///
796/// \param unbridgedCasts a collection to which to add unbridged casts;
797/// without this, they will be immediately diagnosed as errors
798///
799/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000800static bool
801checkPlaceholderForOverload(Sema &S, Expr *&E,
802 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000803 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
804 // We can't handle overloaded expressions here because overload
805 // resolution might reasonably tweak them.
806 if (placeholder->getKind() == BuiltinType::Overload) return false;
807
808 // If the context potentially accepts unbridged ARC casts, strip
809 // the unbridged cast and add it to the collection for later restoration.
810 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
811 unbridgedCasts) {
812 unbridgedCasts->save(S, E);
813 return false;
814 }
815
816 // Go ahead and check everything else.
817 ExprResult result = S.CheckPlaceholderExpr(E);
818 if (result.isInvalid())
819 return true;
820
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000821 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000822 return false;
823 }
824
825 // Nothing to do.
826 return false;
827}
828
829/// checkArgPlaceholdersForOverload - Check a set of call operands for
830/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000831static bool checkArgPlaceholdersForOverload(Sema &S,
832 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000833 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000834 for (unsigned i = 0, e = Args.size(); i != e; ++i)
835 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000836 return true;
837
838 return false;
839}
840
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000841// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000842// overload of the declarations in Old. This routine returns false if
843// New and Old cannot be overloaded, e.g., if New has the same
844// signature as some function in Old (C++ 1.3.10) or if the Old
845// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000846// it does return false, MatchedDecl will point to the decl that New
847// cannot be overloaded with. This decl may be a UsingShadowDecl on
848// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000849//
850// Example: Given the following input:
851//
852// void f(int, float); // #1
853// void f(int, int); // #2
854// int f(int, int); // #3
855//
856// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000857// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000858//
John McCall3d988d92009-12-02 08:47:38 +0000859// When we process #2, Old contains only the FunctionDecl for #1. By
860// comparing the parameter types, we see that #1 and #2 are overloaded
861// (since they have different signatures), so this routine returns
862// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000863//
John McCall3d988d92009-12-02 08:47:38 +0000864// When we process #3, Old is an overload set containing #1 and #2. We
865// compare the signatures of #3 to #1 (they're overloaded, so we do
866// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
867// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000868// signature), IsOverload returns false and MatchedDecl will be set to
869// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000870//
871// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
872// into a class by a using declaration. The rules for whether to hide
873// shadow declarations ignore some properties which otherwise figure
874// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000875Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000876Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
877 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000878 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000879 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000880 NamedDecl *OldD = *I;
881
882 bool OldIsUsingDecl = false;
883 if (isa<UsingShadowDecl>(OldD)) {
884 OldIsUsingDecl = true;
885
886 // We can always introduce two using declarations into the same
887 // context, even if they have identical signatures.
888 if (NewIsUsingDecl) continue;
889
890 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
891 }
892
893 // If either declaration was introduced by a using declaration,
894 // we'll need to use slightly different rules for matching.
895 // Essentially, these rules are the normal rules, except that
896 // function templates hide function templates with different
897 // return types or template parameter lists.
898 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000899 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
900 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000901
Alp Tokera2794f92014-01-22 07:29:52 +0000902 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000903 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
904 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
905 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
906 continue;
907 }
908
Alp Tokera2794f92014-01-22 07:29:52 +0000909 if (!isa<FunctionTemplateDecl>(OldD) &&
910 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000911 continue;
912
John McCalldaa3d6b2009-12-09 03:35:25 +0000913 Match = *I;
914 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000915 }
John McCalla8987a2942010-11-10 03:01:53 +0000916 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000917 // We can overload with these, which can show up when doing
918 // redeclaration checks for UsingDecls.
919 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000920 } else if (isa<TagDecl>(OldD)) {
921 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000922 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
923 // Optimistically assume that an unresolved using decl will
924 // overload; if it doesn't, we'll have to diagnose during
925 // template instantiation.
926 } else {
John McCall1f82f242009-11-18 22:49:29 +0000927 // (C++ 13p1):
928 // Only function declarations can be overloaded; object and type
929 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000930 Match = *I;
931 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000932 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000933 }
John McCall1f82f242009-11-18 22:49:29 +0000934
John McCalldaa3d6b2009-12-09 03:35:25 +0000935 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000936}
937
Richard Smithac974a32013-06-30 09:48:50 +0000938bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
939 bool UseUsingDeclRules) {
940 // C++ [basic.start.main]p2: This function shall not be overloaded.
941 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000942 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000943
David Majnemerc729b0b2013-09-16 22:44:20 +0000944 // MSVCRT user defined entry points cannot be overloaded.
945 if (New->isMSVCRTEntryPoint())
946 return false;
947
John McCall1f82f242009-11-18 22:49:29 +0000948 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
949 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
950
951 // C++ [temp.fct]p2:
952 // A function template can be overloaded with other function templates
953 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +0000954 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +0000955 return true;
956
957 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000958 QualType OldQType = Context.getCanonicalType(Old->getType());
959 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000960
961 // Compare the signatures (C++ 1.3.10) of the two functions to
962 // determine whether they are overloads. If we find any mismatch
963 // in the signature, they are overloads.
964
965 // If either of these functions is a K&R-style function (no
966 // prototype), then we consider them to have matching signatures.
967 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
968 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
969 return false;
970
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000971 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
972 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000973
974 // The signature of a function includes the types of its
975 // parameters (C++ 1.3.10), which includes the presence or absence
976 // of the ellipsis; see C++ DR 357).
977 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +0000978 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +0000979 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000980 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000981 return true;
982
983 // C++ [temp.over.link]p4:
984 // The signature of a function template consists of its function
985 // signature, its return type and its template parameter list. The names
986 // of the template parameters are significant only for establishing the
987 // relationship between the template parameters and the rest of the
988 // signature.
989 //
990 // We check the return type and template parameter lists for function
991 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000992 //
993 // However, we don't consider either of these when deciding whether
994 // a member introduced by a shadow declaration is hidden.
995 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +0000996 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
997 OldTemplate->getTemplateParameters(),
998 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +0000999 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001000 return true;
1001
1002 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001003 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001004 //
1005 // As part of this, also check whether one of the member functions
1006 // is static, in which case they are not overloads (C++
1007 // 13.1p2). While not part of the definition of the signature,
1008 // this check is important to determine whether these functions
1009 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001010 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1011 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001012 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001013 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1014 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1015 if (!UseUsingDeclRules &&
1016 (OldMethod->getRefQualifier() == RQ_None ||
1017 NewMethod->getRefQualifier() == RQ_None)) {
1018 // C++0x [over.load]p2:
1019 // - Member function declarations with the same name and the same
1020 // parameter-type-list as well as member function template
1021 // declarations with the same name, the same parameter-type-list, and
1022 // the same template parameter lists cannot be overloaded if any of
1023 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001024 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001025 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001026 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001027 }
1028 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001030
Richard Smith574f4f62013-01-14 05:37:29 +00001031 // We may not have applied the implicit const for a constexpr member
1032 // function yet (because we haven't yet resolved whether this is a static
1033 // or non-static member function). Add it now, on the assumption that this
1034 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001035 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001036 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001037 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001038 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001039 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001040
1041 // We do not allow overloading based off of '__restrict'.
1042 OldQuals &= ~Qualifiers::Restrict;
1043 NewQuals &= ~Qualifiers::Restrict;
1044 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001045 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001047
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001048 // enable_if attributes are an order-sensitive part of the signature.
1049 for (specific_attr_iterator<EnableIfAttr>
1050 NewI = New->specific_attr_begin<EnableIfAttr>(),
1051 NewE = New->specific_attr_end<EnableIfAttr>(),
1052 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1053 OldE = Old->specific_attr_end<EnableIfAttr>();
1054 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1055 if (NewI == NewE || OldI == OldE)
1056 return true;
1057 llvm::FoldingSetNodeID NewID, OldID;
1058 NewI->getCond()->Profile(NewID, Context, true);
1059 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001060 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001061 return true;
1062 }
1063
John McCall1f82f242009-11-18 22:49:29 +00001064 // The signatures match; this is not an overload.
1065 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001066}
1067
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001068/// \brief Checks availability of the function depending on the current
1069/// function context. Inside an unavailable function, unavailability is ignored.
1070///
1071/// \returns true if \arg FD is unavailable and current context is inside
1072/// an available function, false otherwise.
1073bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1074 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1075}
1076
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001077/// \brief Tries a user-defined conversion from From to ToType.
1078///
1079/// Produces an implicit conversion sequence for when a standard conversion
1080/// is not an option. See TryImplicitConversion for more information.
1081static ImplicitConversionSequence
1082TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1083 bool SuppressUserConversions,
1084 bool AllowExplicit,
1085 bool InOverloadResolution,
1086 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001087 bool AllowObjCWritebackConversion,
1088 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001089 ImplicitConversionSequence ICS;
1090
1091 if (SuppressUserConversions) {
1092 // We're not in the case above, so there is no conversion that
1093 // we can perform.
1094 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1095 return ICS;
1096 }
1097
1098 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001099 OverloadCandidateSet Conversions(From->getExprLoc(),
1100 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001101 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1102 Conversions, AllowExplicit,
1103 AllowObjCConversionOnExplicit)) {
1104 case OR_Success:
1105 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001106 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001107 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001108 // C++ [over.ics.user]p4:
1109 // A conversion of an expression of class type to the same class
1110 // type is given Exact Match rank, and a conversion of an
1111 // expression of class type to a base class of that type is
1112 // given Conversion rank, in spite of the fact that a copy
1113 // constructor (i.e., a user-defined conversion function) is
1114 // called for those cases.
1115 if (CXXConstructorDecl *Constructor
1116 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1117 QualType FromCanon
1118 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1119 QualType ToCanon
1120 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1121 if (Constructor->isCopyConstructor() &&
1122 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1123 // Turn this into a "standard" conversion sequence, so that it
1124 // gets ranked with standard conversion sequences.
1125 ICS.setStandard();
1126 ICS.Standard.setAsIdentityConversion();
1127 ICS.Standard.setFromType(From->getType());
1128 ICS.Standard.setAllToTypes(ToType);
1129 ICS.Standard.CopyConstructor = Constructor;
1130 if (ToCanon != FromCanon)
1131 ICS.Standard.Second = ICK_Derived_To_Base;
1132 }
1133 }
Richard Smith48372b62015-01-27 03:30:40 +00001134 break;
1135
1136 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001137 ICS.setAmbiguous();
1138 ICS.Ambiguous.setFromType(From->getType());
1139 ICS.Ambiguous.setToType(ToType);
1140 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1141 Cand != Conversions.end(); ++Cand)
1142 if (Cand->Viable)
1143 ICS.Ambiguous.addConversion(Cand->Function);
1144 break;
Richard Smith48372b62015-01-27 03:30:40 +00001145
1146 // Fall through.
1147 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001148 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001149 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001150 }
1151
1152 return ICS;
1153}
1154
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001155/// TryImplicitConversion - Attempt to perform an implicit conversion
1156/// from the given expression (Expr) to the given type (ToType). This
1157/// function returns an implicit conversion sequence that can be used
1158/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001159///
1160/// void f(float f);
1161/// void g(int i) { f(i); }
1162///
1163/// this routine would produce an implicit conversion sequence to
1164/// describe the initialization of f from i, which will be a standard
1165/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1166/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1167//
1168/// Note that this routine only determines how the conversion can be
1169/// performed; it does not actually perform the conversion. As such,
1170/// it will not produce any diagnostics if no conversion is available,
1171/// but will instead return an implicit conversion sequence of kind
1172/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001173///
1174/// If @p SuppressUserConversions, then user-defined conversions are
1175/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001176/// If @p AllowExplicit, then explicit user-defined conversions are
1177/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001178///
1179/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1180/// writeback conversion, which allows __autoreleasing id* parameters to
1181/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001182static ImplicitConversionSequence
1183TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1184 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001185 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001186 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001187 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001188 bool AllowObjCWritebackConversion,
1189 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001190 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001191 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001192 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001193 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001194 return ICS;
1195 }
1196
David Blaikiebbafb8a2012-03-11 07:00:24 +00001197 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001198 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001199 return ICS;
1200 }
1201
Douglas Gregor836a7e82010-08-11 02:15:33 +00001202 // C++ [over.ics.user]p4:
1203 // A conversion of an expression of class type to the same class
1204 // type is given Exact Match rank, and a conversion of an
1205 // expression of class type to a base class of that type is
1206 // given Conversion rank, in spite of the fact that a copy/move
1207 // constructor (i.e., a user-defined conversion function) is
1208 // called for those cases.
1209 QualType FromType = From->getType();
1210 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001211 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1212 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001213 ICS.setStandard();
1214 ICS.Standard.setAsIdentityConversion();
1215 ICS.Standard.setFromType(FromType);
1216 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001217
Douglas Gregor5ab11652010-04-17 22:01:05 +00001218 // We don't actually check at this point whether there is a valid
1219 // copy/move constructor, since overloading just assumes that it
1220 // exists. When we actually perform initialization, we'll find the
1221 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001222 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001223
Douglas Gregor5ab11652010-04-17 22:01:05 +00001224 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001225 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001226 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001227
Douglas Gregor836a7e82010-08-11 02:15:33 +00001228 return ICS;
1229 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001230
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001231 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1232 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001233 AllowObjCWritebackConversion,
1234 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001235}
1236
John McCall31168b02011-06-15 23:02:42 +00001237ImplicitConversionSequence
1238Sema::TryImplicitConversion(Expr *From, QualType ToType,
1239 bool SuppressUserConversions,
1240 bool AllowExplicit,
1241 bool InOverloadResolution,
1242 bool CStyle,
1243 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001244 return ::TryImplicitConversion(*this, From, ToType,
1245 SuppressUserConversions, AllowExplicit,
1246 InOverloadResolution, CStyle,
1247 AllowObjCWritebackConversion,
1248 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001249}
1250
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001251/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001252/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001253/// converted expression. Flavor is the kind of conversion we're
1254/// performing, used in the error message. If @p AllowExplicit,
1255/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001256ExprResult
1257Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001258 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001259 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001260 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001261}
1262
John Wiegley01296292011-04-08 18:41:53 +00001263ExprResult
1264Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001265 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001266 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001267 if (checkPlaceholderForOverload(*this, From))
1268 return ExprError();
1269
John McCall31168b02011-06-15 23:02:42 +00001270 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1271 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001272 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001273 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001274 if (getLangOpts().ObjC1)
1275 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1276 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001277 ICS = ::TryImplicitConversion(*this, From, ToType,
1278 /*SuppressUserConversions=*/false,
1279 AllowExplicit,
1280 /*InOverloadResolution=*/false,
1281 /*CStyle=*/false,
1282 AllowObjCWritebackConversion,
1283 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001284 return PerformImplicitConversion(From, ToType, ICS, Action);
1285}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001286
1287/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001288/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001289bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1290 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001291 if (Context.hasSameUnqualifiedType(FromType, ToType))
1292 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001293
John McCall991eb4b2010-12-21 00:44:39 +00001294 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1295 // where F adds one of the following at most once:
1296 // - a pointer
1297 // - a member pointer
1298 // - a block pointer
1299 CanQualType CanTo = Context.getCanonicalType(ToType);
1300 CanQualType CanFrom = Context.getCanonicalType(FromType);
1301 Type::TypeClass TyClass = CanTo->getTypeClass();
1302 if (TyClass != CanFrom->getTypeClass()) return false;
1303 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1304 if (TyClass == Type::Pointer) {
1305 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1306 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1307 } else if (TyClass == Type::BlockPointer) {
1308 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1309 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1310 } else if (TyClass == Type::MemberPointer) {
1311 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1312 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1313 } else {
1314 return false;
1315 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001316
John McCall991eb4b2010-12-21 00:44:39 +00001317 TyClass = CanTo->getTypeClass();
1318 if (TyClass != CanFrom->getTypeClass()) return false;
1319 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1320 return false;
1321 }
1322
1323 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1324 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1325 if (!EInfo.getNoReturn()) return false;
1326
1327 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1328 assert(QualType(FromFn, 0).isCanonical());
1329 if (QualType(FromFn, 0) != CanTo) return false;
1330
1331 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001332 return true;
1333}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001334
Douglas Gregor46188682010-05-18 22:42:18 +00001335/// \brief Determine whether the conversion from FromType to ToType is a valid
1336/// vector conversion.
1337///
1338/// \param ICK Will be set to the vector conversion kind, if this is a vector
1339/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001340static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001341 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001342 // We need at least one of these types to be a vector type to have a vector
1343 // conversion.
1344 if (!ToType->isVectorType() && !FromType->isVectorType())
1345 return false;
1346
1347 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001348 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001349 return false;
1350
1351 // There are no conversions between extended vector types, only identity.
1352 if (ToType->isExtVectorType()) {
1353 // There are no conversions between extended vector types other than the
1354 // identity conversion.
1355 if (FromType->isExtVectorType())
1356 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357
Douglas Gregor46188682010-05-18 22:42:18 +00001358 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001359 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001360 ICK = ICK_Vector_Splat;
1361 return true;
1362 }
1363 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001364
1365 // We can perform the conversion between vector types in the following cases:
1366 // 1)vector types are equivalent AltiVec and GCC vector types
1367 // 2)lax vector conversions are permitted and the vector types are of the
1368 // same size
1369 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001370 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1371 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001372 ICK = ICK_Vector_Conversion;
1373 return true;
1374 }
Douglas Gregor46188682010-05-18 22:42:18 +00001375 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001376
Douglas Gregor46188682010-05-18 22:42:18 +00001377 return false;
1378}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001379
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001380static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1381 bool InOverloadResolution,
1382 StandardConversionSequence &SCS,
1383 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001384
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001385/// IsStandardConversion - Determines whether there is a standard
1386/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1387/// expression From to the type ToType. Standard conversion sequences
1388/// only consider non-class types; for conversions that involve class
1389/// types, use TryImplicitConversion. If a conversion exists, SCS will
1390/// contain the standard conversion sequence required to perform this
1391/// conversion and this routine will return true. Otherwise, this
1392/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001393static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1394 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001395 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001396 bool CStyle,
1397 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001398 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001400 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001401 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001402 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001403 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001404 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001405
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001406 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001407 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001408 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001409 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001410 return false;
1411
Mike Stump11289f42009-09-09 15:08:12 +00001412 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001413 }
1414
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001415 // The first conversion can be an lvalue-to-rvalue conversion,
1416 // array-to-pointer conversion, or function-to-pointer conversion
1417 // (C++ 4p1).
1418
John McCall5c32be02010-08-24 20:38:10 +00001419 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001420 DeclAccessPair AccessPair;
1421 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001423 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001424 // We were able to resolve the address of the overloaded function,
1425 // so we can convert to the type of that function.
1426 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001427 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001428
1429 // we can sometimes resolve &foo<int> regardless of ToType, so check
1430 // if the type matches (identity) or we are converting to bool
1431 if (!S.Context.hasSameUnqualifiedType(
1432 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1433 QualType resultTy;
1434 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001435 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001436 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1437 // otherwise, only a boolean conversion is standard
1438 if (!ToType->isBooleanType())
1439 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001441
Chandler Carruthffce2452011-03-29 08:08:18 +00001442 // Check if the "from" expression is taking the address of an overloaded
1443 // function and recompute the FromType accordingly. Take advantage of the
1444 // fact that non-static member functions *must* have such an address-of
1445 // expression.
1446 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1447 if (Method && !Method->isStatic()) {
1448 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1449 "Non-unary operator on non-static member address");
1450 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1451 == UO_AddrOf &&
1452 "Non-address-of operator on non-static member address");
1453 const Type *ClassType
1454 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1455 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001456 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1457 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1458 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001459 "Non-address-of operator for overloaded function expression");
1460 FromType = S.Context.getPointerType(FromType);
1461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001462
Douglas Gregor980fb162010-04-29 18:24:40 +00001463 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001464 assert(S.Context.hasSameType(
1465 FromType,
1466 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001467 } else {
1468 return false;
1469 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001470 }
John McCall154a2fd2011-08-30 00:57:29 +00001471 // Lvalue-to-rvalue conversion (C++11 4.1):
1472 // A glvalue (3.10) of a non-function, non-array type T can
1473 // be converted to a prvalue.
1474 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001475 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001476 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001477 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001478 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001479
Douglas Gregorc79862f2012-04-12 17:51:55 +00001480 // C11 6.3.2.1p2:
1481 // ... if the lvalue has atomic type, the value has the non-atomic version
1482 // of the type of the lvalue ...
1483 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1484 FromType = Atomic->getValueType();
1485
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001486 // If T is a non-class type, the type of the rvalue is the
1487 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001488 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1489 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001490 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001491 } else if (FromType->isArrayType()) {
1492 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001493 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001494
1495 // An lvalue or rvalue of type "array of N T" or "array of unknown
1496 // bound of T" can be converted to an rvalue of type "pointer to
1497 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001498 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001499
John McCall5c32be02010-08-24 20:38:10 +00001500 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001501 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001502 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001503
1504 // For the purpose of ranking in overload resolution
1505 // (13.3.3.1.1), this conversion is considered an
1506 // array-to-pointer conversion followed by a qualification
1507 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001508 SCS.Second = ICK_Identity;
1509 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001510 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001511 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001512 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001513 }
John McCall086a4642010-11-24 05:12:34 +00001514 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001515 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001516 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001517
1518 // An lvalue of function type T can be converted to an rvalue of
1519 // type "pointer to T." The result is a pointer to the
1520 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001521 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001522 } else {
1523 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001524 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001525 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001526 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001527
1528 // The second conversion can be an integral promotion, floating
1529 // point promotion, integral conversion, floating point conversion,
1530 // floating-integral conversion, pointer conversion,
1531 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001532 // For overloading in C, this can also be a "compatible-type"
1533 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001534 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001535 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001536 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001537 // The unqualified versions of the types are the same: there's no
1538 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001539 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001540 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001541 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001542 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001543 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001544 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001545 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001546 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001547 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001548 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001549 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001550 SCS.Second = ICK_Complex_Promotion;
1551 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001552 } else if (ToType->isBooleanType() &&
1553 (FromType->isArithmeticType() ||
1554 FromType->isAnyPointerType() ||
1555 FromType->isBlockPointerType() ||
1556 FromType->isMemberPointerType() ||
1557 FromType->isNullPtrType())) {
1558 // Boolean conversions (C++ 4.12).
1559 SCS.Second = ICK_Boolean_Conversion;
1560 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001561 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001562 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001563 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001564 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001565 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001566 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001567 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001568 SCS.Second = ICK_Complex_Conversion;
1569 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001570 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1571 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001572 // Complex-real conversions (C99 6.3.1.7)
1573 SCS.Second = ICK_Complex_Real;
1574 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001575 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001576 // Floating point conversions (C++ 4.8).
1577 SCS.Second = ICK_Floating_Conversion;
1578 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001579 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001580 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001581 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001582 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001583 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001584 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001585 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001586 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001587 SCS.Second = ICK_Block_Pointer_Conversion;
1588 } else if (AllowObjCWritebackConversion &&
1589 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1590 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001591 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1592 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001593 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001594 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001595 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001596 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001597 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001598 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001599 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001600 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001601 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001602 SCS.Second = SecondICK;
1603 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001604 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001605 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001606 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001607 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001608 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001609 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001610 // Treat a conversion that strips "noreturn" as an identity conversion.
1611 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001612 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1613 InOverloadResolution,
1614 SCS, CStyle)) {
1615 SCS.Second = ICK_TransparentUnionConversion;
1616 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001617 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1618 CStyle)) {
1619 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001620 // appropriately.
1621 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001622 } else if (ToType->isEventT() &&
1623 From->isIntegerConstantExpr(S.getASTContext()) &&
1624 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1625 SCS.Second = ICK_Zero_Event_Conversion;
1626 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001627 } else {
1628 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001629 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001630 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001631 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001632
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001633 QualType CanonFrom;
1634 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001635 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001636 bool ObjCLifetimeConversion;
1637 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1638 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001639 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001640 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001641 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001642 CanonFrom = S.Context.getCanonicalType(FromType);
1643 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001644 } else {
1645 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001646 SCS.Third = ICK_Identity;
1647
Mike Stump11289f42009-09-09 15:08:12 +00001648 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001649 // [...] Any difference in top-level cv-qualification is
1650 // subsumed by the initialization itself and does not constitute
1651 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001652 CanonFrom = S.Context.getCanonicalType(FromType);
1653 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001654 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001655 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001656 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001657 FromType = ToType;
1658 CanonFrom = CanonTo;
1659 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001660 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001661 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001662
1663 // If we have not converted the argument type to the parameter type,
1664 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001665 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001666 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001667
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001668 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001669}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001670
1671static bool
1672IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1673 QualType &ToType,
1674 bool InOverloadResolution,
1675 StandardConversionSequence &SCS,
1676 bool CStyle) {
1677
1678 const RecordType *UT = ToType->getAsUnionType();
1679 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1680 return false;
1681 // The field to initialize within the transparent union.
1682 RecordDecl *UD = UT->getDecl();
1683 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001684 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001685 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1686 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001687 ToType = it->getType();
1688 return true;
1689 }
1690 }
1691 return false;
1692}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001693
1694/// IsIntegralPromotion - Determines whether the conversion from the
1695/// expression From (whose potentially-adjusted type is FromType) to
1696/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1697/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001698bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001699 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001700 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001701 if (!To) {
1702 return false;
1703 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001704
1705 // An rvalue of type char, signed char, unsigned char, short int, or
1706 // unsigned short int can be converted to an rvalue of type int if
1707 // int can represent all the values of the source type; otherwise,
1708 // the source rvalue can be converted to an rvalue of type unsigned
1709 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001710 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1711 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001712 if (// We can promote any signed, promotable integer type to an int
1713 (FromType->isSignedIntegerType() ||
1714 // We can promote any unsigned integer type whose size is
1715 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001716 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001717 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001719 }
1720
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001721 return To->getKind() == BuiltinType::UInt;
1722 }
1723
Richard Smithb9c5a602012-09-13 21:18:54 +00001724 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725 // A prvalue of an unscoped enumeration type whose underlying type is not
1726 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1727 // following types that can represent all the values of the enumeration
1728 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1729 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001730 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001731 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001732 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001733 // with lowest integer conversion rank (4.13) greater than the rank of long
1734 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001735 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001736 // C++11 [conv.prom]p4:
1737 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1738 // can be converted to a prvalue of its underlying type. Moreover, if
1739 // integral promotion can be applied to its underlying type, a prvalue of an
1740 // unscoped enumeration type whose underlying type is fixed can also be
1741 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001742 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1743 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1744 // provided for a scoped enumeration.
1745 if (FromEnumType->getDecl()->isScoped())
1746 return false;
1747
Richard Smithb9c5a602012-09-13 21:18:54 +00001748 // We can perform an integral promotion to the underlying type of the enum,
1749 // even if that's not the promoted type.
1750 if (FromEnumType->getDecl()->isFixed()) {
1751 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1752 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1753 IsIntegralPromotion(From, Underlying, ToType);
1754 }
1755
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001756 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001757 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001758 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001759 return Context.hasSameUnqualifiedType(ToType,
1760 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001761 }
John McCall56774992009-12-09 09:09:27 +00001762
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001763 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001764 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1765 // to an rvalue a prvalue of the first of the following types that can
1766 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001767 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001768 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001769 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001770 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001771 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001772 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001773 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001774 // Determine whether the type we're converting from is signed or
1775 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001776 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001777 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001778
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001779 // The types we'll try to promote to, in the appropriate
1780 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001781 QualType PromoteTypes[6] = {
1782 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001783 Context.LongTy, Context.UnsignedLongTy ,
1784 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001785 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001786 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001787 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1788 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001789 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001790 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1791 // We found the type that we can promote to. If this is the
1792 // type we wanted, we have a promotion. Otherwise, no
1793 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001794 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001795 }
1796 }
1797 }
1798
1799 // An rvalue for an integral bit-field (9.6) can be converted to an
1800 // rvalue of type int if int can represent all the values of the
1801 // bit-field; otherwise, it can be converted to unsigned int if
1802 // unsigned int can represent all the values of the bit-field. If
1803 // the bit-field is larger yet, no integral promotion applies to
1804 // it. If the bit-field has an enumerated type, it is treated as any
1805 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001806 // FIXME: We should delay checking of bit-fields until we actually perform the
1807 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001808 using llvm::APSInt;
1809 if (From)
John McCalld25db7e2013-05-06 21:39:12 +00001810 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001811 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001812 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001813 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1814 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1815 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001816
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001817 // Are we promoting to an int from a bitfield that fits in an int?
1818 if (BitWidth < ToSize ||
1819 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1820 return To->getKind() == BuiltinType::Int;
1821 }
Mike Stump11289f42009-09-09 15:08:12 +00001822
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001823 // Are we promoting to an unsigned int from an unsigned bitfield
1824 // that fits into an unsigned int?
1825 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1826 return To->getKind() == BuiltinType::UInt;
1827 }
Mike Stump11289f42009-09-09 15:08:12 +00001828
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001829 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001830 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001831 }
Mike Stump11289f42009-09-09 15:08:12 +00001832
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001833 // An rvalue of type bool can be converted to an rvalue of type int,
1834 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001835 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001836 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001837 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001838
1839 return false;
1840}
1841
1842/// IsFloatingPointPromotion - Determines whether the conversion from
1843/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1844/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001845bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001846 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1847 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001848 /// An rvalue of type float can be converted to an rvalue of type
1849 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001850 if (FromBuiltin->getKind() == BuiltinType::Float &&
1851 ToBuiltin->getKind() == BuiltinType::Double)
1852 return true;
1853
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001854 // C99 6.3.1.5p1:
1855 // When a float is promoted to double or long double, or a
1856 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001857 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001858 (FromBuiltin->getKind() == BuiltinType::Float ||
1859 FromBuiltin->getKind() == BuiltinType::Double) &&
1860 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1861 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001862
1863 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001864 if (!getLangOpts().NativeHalfType &&
1865 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001866 ToBuiltin->getKind() == BuiltinType::Float)
1867 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001868 }
1869
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001870 return false;
1871}
1872
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001873/// \brief Determine if a conversion is a complex promotion.
1874///
1875/// A complex promotion is defined as a complex -> complex conversion
1876/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001877/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001878bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001879 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001880 if (!FromComplex)
1881 return false;
1882
John McCall9dd450b2009-09-21 23:43:11 +00001883 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001884 if (!ToComplex)
1885 return false;
1886
1887 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001888 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001889 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001890 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001891}
1892
Douglas Gregor237f96c2008-11-26 23:31:11 +00001893/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1894/// the pointer type FromPtr to a pointer to type ToPointee, with the
1895/// same type qualifiers as FromPtr has on its pointee type. ToType,
1896/// if non-empty, will be a pointer to ToType that may or may not have
1897/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001898///
Mike Stump11289f42009-09-09 15:08:12 +00001899static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001900BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001901 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001902 ASTContext &Context,
1903 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001904 assert((FromPtr->getTypeClass() == Type::Pointer ||
1905 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1906 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001907
John McCall31168b02011-06-15 23:02:42 +00001908 /// Conversions to 'id' subsume cv-qualifier conversions.
1909 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001910 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001911
1912 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001913 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001914 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001915 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001916
John McCall31168b02011-06-15 23:02:42 +00001917 if (StripObjCLifetime)
1918 Quals.removeObjCLifetime();
1919
Mike Stump11289f42009-09-09 15:08:12 +00001920 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001921 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001922 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001923 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001924 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001925
1926 // Build a pointer to ToPointee. It has the right qualifiers
1927 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001928 if (isa<ObjCObjectPointerType>(ToType))
1929 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001930 return Context.getPointerType(ToPointee);
1931 }
1932
1933 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001934 QualType QualifiedCanonToPointee
1935 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001936
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001937 if (isa<ObjCObjectPointerType>(ToType))
1938 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1939 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001940}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001941
Mike Stump11289f42009-09-09 15:08:12 +00001942static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001943 bool InOverloadResolution,
1944 ASTContext &Context) {
1945 // Handle value-dependent integral null pointer constants correctly.
1946 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1947 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001948 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001949 return !InOverloadResolution;
1950
Douglas Gregor56751b52009-09-25 04:25:58 +00001951 return Expr->isNullPointerConstant(Context,
1952 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1953 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001954}
Mike Stump11289f42009-09-09 15:08:12 +00001955
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001956/// IsPointerConversion - Determines whether the conversion of the
1957/// expression From, which has the (possibly adjusted) type FromType,
1958/// can be converted to the type ToType via a pointer conversion (C++
1959/// 4.10). If so, returns true and places the converted type (that
1960/// might differ from ToType in its cv-qualifiers at some level) into
1961/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001962///
Douglas Gregora29dc052008-11-27 01:19:21 +00001963/// This routine also supports conversions to and from block pointers
1964/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1965/// pointers to interfaces. FIXME: Once we've determined the
1966/// appropriate overloading rules for Objective-C, we may want to
1967/// split the Objective-C checks into a different routine; however,
1968/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001969/// conversions, so for now they live here. IncompatibleObjC will be
1970/// set if the conversion is an allowed Objective-C conversion that
1971/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001972bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001973 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001974 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001975 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001976 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001977 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1978 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001979 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001980
Mike Stump11289f42009-09-09 15:08:12 +00001981 // Conversion from a null pointer constant to any Objective-C pointer type.
1982 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001983 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001984 ConvertedType = ToType;
1985 return true;
1986 }
1987
Douglas Gregor231d1c62008-11-27 00:15:41 +00001988 // Blocks: Block pointers can be converted to void*.
1989 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001990 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001991 ConvertedType = ToType;
1992 return true;
1993 }
1994 // Blocks: A null pointer constant can be converted to a block
1995 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001996 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001997 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001998 ConvertedType = ToType;
1999 return true;
2000 }
2001
Sebastian Redl576fd422009-05-10 18:38:11 +00002002 // If the left-hand-side is nullptr_t, the right side can be a null
2003 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002004 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002005 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002006 ConvertedType = ToType;
2007 return true;
2008 }
2009
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002010 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002011 if (!ToTypePtr)
2012 return false;
2013
2014 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002015 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002016 ConvertedType = ToType;
2017 return true;
2018 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002019
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002020 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002021 // , including objective-c pointers.
2022 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002023 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002024 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002025 ConvertedType = BuildSimilarlyQualifiedPointerType(
2026 FromType->getAs<ObjCObjectPointerType>(),
2027 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002028 ToType, Context);
2029 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002030 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002031 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002032 if (!FromTypePtr)
2033 return false;
2034
2035 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002036
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002037 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002038 // pointer conversion, so don't do all of the work below.
2039 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2040 return false;
2041
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002042 // An rvalue of type "pointer to cv T," where T is an object type,
2043 // can be converted to an rvalue of type "pointer to cv void" (C++
2044 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002045 if (FromPointeeType->isIncompleteOrObjectType() &&
2046 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002047 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002048 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002049 ToType, Context,
2050 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002051 return true;
2052 }
2053
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002054 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002055 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002056 ToPointeeType->isVoidType()) {
2057 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2058 ToPointeeType,
2059 ToType, Context);
2060 return true;
2061 }
2062
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002063 // When we're overloading in C, we allow a special kind of pointer
2064 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002065 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002066 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002067 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002068 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002069 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002070 return true;
2071 }
2072
Douglas Gregor5c407d92008-10-23 00:40:37 +00002073 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002074 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002075 // An rvalue of type "pointer to cv D," where D is a class type,
2076 // can be converted to an rvalue of type "pointer to cv B," where
2077 // B is a base class (clause 10) of D. If B is an inaccessible
2078 // (clause 11) or ambiguous (10.2) base class of D, a program that
2079 // necessitates this conversion is ill-formed. The result of the
2080 // conversion is a pointer to the base class sub-object of the
2081 // derived class object. The null pointer value is converted to
2082 // the null pointer value of the destination type.
2083 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002084 // Note that we do not check for ambiguity or inaccessibility
2085 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002086 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002087 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002088 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002089 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002090 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002091 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002092 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002093 ToType, Context);
2094 return true;
2095 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002096
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002097 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2098 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2100 ToPointeeType,
2101 ToType, Context);
2102 return true;
2103 }
2104
Douglas Gregora119f102008-12-19 19:13:09 +00002105 return false;
2106}
Douglas Gregoraec25842011-04-26 23:16:46 +00002107
2108/// \brief Adopt the given qualifiers for the given type.
2109static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2110 Qualifiers TQs = T.getQualifiers();
2111
2112 // Check whether qualifiers already match.
2113 if (TQs == Qs)
2114 return T;
2115
2116 if (Qs.compatiblyIncludes(TQs))
2117 return Context.getQualifiedType(T, Qs);
2118
2119 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2120}
Douglas Gregora119f102008-12-19 19:13:09 +00002121
2122/// isObjCPointerConversion - Determines whether this is an
2123/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2124/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002125bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002126 QualType& ConvertedType,
2127 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002128 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002129 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130
Douglas Gregoraec25842011-04-26 23:16:46 +00002131 // The set of qualifiers on the type we're converting from.
2132 Qualifiers FromQualifiers = FromType.getQualifiers();
2133
Steve Naroff7cae42b2009-07-10 23:34:53 +00002134 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002135 const ObjCObjectPointerType* ToObjCPtr =
2136 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002137 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002138 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002139
Steve Naroff7cae42b2009-07-10 23:34:53 +00002140 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002141 // If the pointee types are the same (ignoring qualifications),
2142 // then this is not a pointer conversion.
2143 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2144 FromObjCPtr->getPointeeType()))
2145 return false;
2146
Douglas Gregoraec25842011-04-26 23:16:46 +00002147 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002148 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002149 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002150 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002151 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002152 return true;
2153 }
2154 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002155 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002156 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002157 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002158 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002159 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002160 return true;
2161 }
2162 // Objective C++: We're able to convert from a pointer to an
2163 // interface to a pointer to a different interface.
2164 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002165 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2166 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002167 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002168 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2169 FromObjCPtr->getPointeeType()))
2170 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002171 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002172 ToObjCPtr->getPointeeType(),
2173 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002174 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002175 return true;
2176 }
2177
2178 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2179 // Okay: this is some kind of implicit downcast of Objective-C
2180 // interfaces, which is permitted. However, we're going to
2181 // complain about it.
2182 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002183 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002184 ToObjCPtr->getPointeeType(),
2185 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002186 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002187 return true;
2188 }
Mike Stump11289f42009-09-09 15:08:12 +00002189 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002190 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002191 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002192 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002193 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002194 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002195 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002196 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002197 // to a block pointer type.
2198 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002199 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002200 return true;
2201 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002202 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002204 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002205 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002206 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002207 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002208 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002209 return true;
2210 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002211 else
Douglas Gregora119f102008-12-19 19:13:09 +00002212 return false;
2213
Douglas Gregor033f56d2008-12-23 00:53:59 +00002214 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002215 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002216 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002217 else if (const BlockPointerType *FromBlockPtr =
2218 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002219 FromPointeeType = FromBlockPtr->getPointeeType();
2220 else
Douglas Gregora119f102008-12-19 19:13:09 +00002221 return false;
2222
Douglas Gregora119f102008-12-19 19:13:09 +00002223 // If we have pointers to pointers, recursively check whether this
2224 // is an Objective-C conversion.
2225 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2226 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2227 IncompatibleObjC)) {
2228 // We always complain about this conversion.
2229 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002230 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002231 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002232 return true;
2233 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002234 // Allow conversion of pointee being objective-c pointer to another one;
2235 // as in I* to id.
2236 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2237 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2238 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2239 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002240
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002241 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002242 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002243 return true;
2244 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002245
Douglas Gregor033f56d2008-12-23 00:53:59 +00002246 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002247 // differences in the argument and result types are in Objective-C
2248 // pointer conversions. If so, we permit the conversion (but
2249 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002250 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002251 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002252 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002253 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002254 if (FromFunctionType && ToFunctionType) {
2255 // If the function types are exactly the same, this isn't an
2256 // Objective-C pointer conversion.
2257 if (Context.getCanonicalType(FromPointeeType)
2258 == Context.getCanonicalType(ToPointeeType))
2259 return false;
2260
2261 // Perform the quick checks that will tell us whether these
2262 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002263 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002264 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2265 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2266 return false;
2267
2268 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002269 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2270 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002271 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002272 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2273 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002274 ConvertedType, IncompatibleObjC)) {
2275 // Okay, we have an Objective-C pointer conversion.
2276 HasObjCConversion = true;
2277 } else {
2278 // Function types are too different. Abort.
2279 return false;
2280 }
Mike Stump11289f42009-09-09 15:08:12 +00002281
Douglas Gregora119f102008-12-19 19:13:09 +00002282 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002283 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002284 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002285 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2286 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002287 if (Context.getCanonicalType(FromArgType)
2288 == Context.getCanonicalType(ToArgType)) {
2289 // Okay, the types match exactly. Nothing to do.
2290 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2291 ConvertedType, IncompatibleObjC)) {
2292 // Okay, we have an Objective-C pointer conversion.
2293 HasObjCConversion = true;
2294 } else {
2295 // Argument types are too different. Abort.
2296 return false;
2297 }
2298 }
2299
2300 if (HasObjCConversion) {
2301 // We had an Objective-C conversion. Allow this pointer
2302 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002303 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002304 IncompatibleObjC = true;
2305 return true;
2306 }
2307 }
2308
Sebastian Redl72b597d2009-01-25 19:43:20 +00002309 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002310}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002311
John McCall31168b02011-06-15 23:02:42 +00002312/// \brief Determine whether this is an Objective-C writeback conversion,
2313/// used for parameter passing when performing automatic reference counting.
2314///
2315/// \param FromType The type we're converting form.
2316///
2317/// \param ToType The type we're converting to.
2318///
2319/// \param ConvertedType The type that will be produced after applying
2320/// this conversion.
2321bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2322 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002323 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002324 Context.hasSameUnqualifiedType(FromType, ToType))
2325 return false;
2326
2327 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2328 QualType ToPointee;
2329 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2330 ToPointee = ToPointer->getPointeeType();
2331 else
2332 return false;
2333
2334 Qualifiers ToQuals = ToPointee.getQualifiers();
2335 if (!ToPointee->isObjCLifetimeType() ||
2336 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002337 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002338 return false;
2339
2340 // Argument must be a pointer to __strong to __weak.
2341 QualType FromPointee;
2342 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2343 FromPointee = FromPointer->getPointeeType();
2344 else
2345 return false;
2346
2347 Qualifiers FromQuals = FromPointee.getQualifiers();
2348 if (!FromPointee->isObjCLifetimeType() ||
2349 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2350 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2351 return false;
2352
2353 // Make sure that we have compatible qualifiers.
2354 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2355 if (!ToQuals.compatiblyIncludes(FromQuals))
2356 return false;
2357
2358 // Remove qualifiers from the pointee type we're converting from; they
2359 // aren't used in the compatibility check belong, and we'll be adding back
2360 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2361 FromPointee = FromPointee.getUnqualifiedType();
2362
2363 // The unqualified form of the pointee types must be compatible.
2364 ToPointee = ToPointee.getUnqualifiedType();
2365 bool IncompatibleObjC;
2366 if (Context.typesAreCompatible(FromPointee, ToPointee))
2367 FromPointee = ToPointee;
2368 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2369 IncompatibleObjC))
2370 return false;
2371
2372 /// \brief Construct the type we're converting to, which is a pointer to
2373 /// __autoreleasing pointee.
2374 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2375 ConvertedType = Context.getPointerType(FromPointee);
2376 return true;
2377}
2378
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002379bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2380 QualType& ConvertedType) {
2381 QualType ToPointeeType;
2382 if (const BlockPointerType *ToBlockPtr =
2383 ToType->getAs<BlockPointerType>())
2384 ToPointeeType = ToBlockPtr->getPointeeType();
2385 else
2386 return false;
2387
2388 QualType FromPointeeType;
2389 if (const BlockPointerType *FromBlockPtr =
2390 FromType->getAs<BlockPointerType>())
2391 FromPointeeType = FromBlockPtr->getPointeeType();
2392 else
2393 return false;
2394 // We have pointer to blocks, check whether the only
2395 // differences in the argument and result types are in Objective-C
2396 // pointer conversions. If so, we permit the conversion.
2397
2398 const FunctionProtoType *FromFunctionType
2399 = FromPointeeType->getAs<FunctionProtoType>();
2400 const FunctionProtoType *ToFunctionType
2401 = ToPointeeType->getAs<FunctionProtoType>();
2402
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002403 if (!FromFunctionType || !ToFunctionType)
2404 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002405
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002406 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002407 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002408
2409 // Perform the quick checks that will tell us whether these
2410 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002411 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002412 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2413 return false;
2414
2415 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2416 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2417 if (FromEInfo != ToEInfo)
2418 return false;
2419
2420 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002421 if (Context.hasSameType(FromFunctionType->getReturnType(),
2422 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002423 // Okay, the types match exactly. Nothing to do.
2424 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002425 QualType RHS = FromFunctionType->getReturnType();
2426 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002427 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002428 !RHS.hasQualifiers() && LHS.hasQualifiers())
2429 LHS = LHS.getUnqualifiedType();
2430
2431 if (Context.hasSameType(RHS,LHS)) {
2432 // OK exact match.
2433 } else if (isObjCPointerConversion(RHS, LHS,
2434 ConvertedType, IncompatibleObjC)) {
2435 if (IncompatibleObjC)
2436 return false;
2437 // Okay, we have an Objective-C pointer conversion.
2438 }
2439 else
2440 return false;
2441 }
2442
2443 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002444 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002445 ArgIdx != NumArgs; ++ArgIdx) {
2446 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002447 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2448 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002449 if (Context.hasSameType(FromArgType, ToArgType)) {
2450 // Okay, the types match exactly. Nothing to do.
2451 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2452 ConvertedType, IncompatibleObjC)) {
2453 if (IncompatibleObjC)
2454 return false;
2455 // Okay, we have an Objective-C pointer conversion.
2456 } else
2457 // Argument types are too different. Abort.
2458 return false;
2459 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002460 if (LangOpts.ObjCAutoRefCount &&
2461 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2462 ToFunctionType))
2463 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002464
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002465 ConvertedType = ToType;
2466 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002467}
2468
Richard Trieucaff2472011-11-23 22:32:32 +00002469enum {
2470 ft_default,
2471 ft_different_class,
2472 ft_parameter_arity,
2473 ft_parameter_mismatch,
2474 ft_return_type,
2475 ft_qualifer_mismatch
2476};
2477
2478/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2479/// function types. Catches different number of parameter, mismatch in
2480/// parameter types, and different return types.
2481void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2482 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002483 // If either type is not valid, include no extra info.
2484 if (FromType.isNull() || ToType.isNull()) {
2485 PDiag << ft_default;
2486 return;
2487 }
2488
Richard Trieucaff2472011-11-23 22:32:32 +00002489 // Get the function type from the pointers.
2490 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2491 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2492 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002493 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002494 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2495 << QualType(FromMember->getClass(), 0);
2496 return;
2497 }
2498 FromType = FromMember->getPointeeType();
2499 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002500 }
2501
Richard Trieu96ed5b62011-12-13 23:19:45 +00002502 if (FromType->isPointerType())
2503 FromType = FromType->getPointeeType();
2504 if (ToType->isPointerType())
2505 ToType = ToType->getPointeeType();
2506
2507 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002508 FromType = FromType.getNonReferenceType();
2509 ToType = ToType.getNonReferenceType();
2510
Richard Trieucaff2472011-11-23 22:32:32 +00002511 // Don't print extra info for non-specialized template functions.
2512 if (FromType->isInstantiationDependentType() &&
2513 !FromType->getAs<TemplateSpecializationType>()) {
2514 PDiag << ft_default;
2515 return;
2516 }
2517
Richard Trieu96ed5b62011-12-13 23:19:45 +00002518 // No extra info for same types.
2519 if (Context.hasSameType(FromType, ToType)) {
2520 PDiag << ft_default;
2521 return;
2522 }
2523
Richard Trieucaff2472011-11-23 22:32:32 +00002524 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2525 *ToFunction = ToType->getAs<FunctionProtoType>();
2526
2527 // Both types need to be function types.
2528 if (!FromFunction || !ToFunction) {
2529 PDiag << ft_default;
2530 return;
2531 }
2532
Alp Toker9cacbab2014-01-20 20:26:09 +00002533 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2534 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2535 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002536 return;
2537 }
2538
2539 // Handle different parameter types.
2540 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002541 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002542 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002543 << ToFunction->getParamType(ArgPos)
2544 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002545 return;
2546 }
2547
2548 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002549 if (!Context.hasSameType(FromFunction->getReturnType(),
2550 ToFunction->getReturnType())) {
2551 PDiag << ft_return_type << ToFunction->getReturnType()
2552 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002553 return;
2554 }
2555
2556 unsigned FromQuals = FromFunction->getTypeQuals(),
2557 ToQuals = ToFunction->getTypeQuals();
2558 if (FromQuals != ToQuals) {
2559 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2560 return;
2561 }
2562
2563 // Unable to find a difference, so add no extra info.
2564 PDiag << ft_default;
2565}
2566
Alp Toker9cacbab2014-01-20 20:26:09 +00002567/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002568/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002569/// they have same number of arguments. If the parameters are different,
2570/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002571bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2572 const FunctionProtoType *NewType,
2573 unsigned *ArgPos) {
2574 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2575 N = NewType->param_type_begin(),
2576 E = OldType->param_type_end();
2577 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002578 if (!Context.hasSameType(O->getUnqualifiedType(),
2579 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002580 if (ArgPos)
2581 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002582 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002583 }
2584 }
2585 return true;
2586}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002587
Douglas Gregor39c16d42008-10-24 04:54:22 +00002588/// CheckPointerConversion - Check the pointer conversion from the
2589/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002590/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002591/// conversions for which IsPointerConversion has already returned
2592/// true. It returns true and produces a diagnostic if there was an
2593/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002594bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002595 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002596 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002597 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002598 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002599 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002600
John McCall8cb679e2010-11-15 09:13:47 +00002601 Kind = CK_BitCast;
2602
David Blaikie1c7c8f72012-08-08 17:33:31 +00002603 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002604 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002605 Expr::NPCK_ZeroExpression) {
2606 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2607 DiagRuntimeBehavior(From->getExprLoc(), From,
2608 PDiag(diag::warn_impcast_bool_to_null_pointer)
2609 << ToType << From->getSourceRange());
2610 else if (!isUnevaluatedContext())
2611 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2612 << ToType << From->getSourceRange();
2613 }
John McCall9320b872011-09-09 05:25:32 +00002614 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2615 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002616 QualType FromPointeeType = FromPtrType->getPointeeType(),
2617 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002618
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002619 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2620 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002621 // We must have a derived-to-base conversion. Check an
2622 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002623 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2624 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002625 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002626 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002627 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002628
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002629 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002630 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002631 }
2632 }
John McCall9320b872011-09-09 05:25:32 +00002633 } else if (const ObjCObjectPointerType *ToPtrType =
2634 ToType->getAs<ObjCObjectPointerType>()) {
2635 if (const ObjCObjectPointerType *FromPtrType =
2636 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002637 // Objective-C++ conversions are always okay.
2638 // FIXME: We should have a different class of conversions for the
2639 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002640 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002641 return false;
John McCall9320b872011-09-09 05:25:32 +00002642 } else if (FromType->isBlockPointerType()) {
2643 Kind = CK_BlockPointerToObjCPointerCast;
2644 } else {
2645 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002646 }
John McCall9320b872011-09-09 05:25:32 +00002647 } else if (ToType->isBlockPointerType()) {
2648 if (!FromType->isBlockPointerType())
2649 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002650 }
John McCall8cb679e2010-11-15 09:13:47 +00002651
2652 // We shouldn't fall into this case unless it's valid for other
2653 // reasons.
2654 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2655 Kind = CK_NullToPointer;
2656
Douglas Gregor39c16d42008-10-24 04:54:22 +00002657 return false;
2658}
2659
Sebastian Redl72b597d2009-01-25 19:43:20 +00002660/// IsMemberPointerConversion - Determines whether the conversion of the
2661/// expression From, which has the (possibly adjusted) type FromType, can be
2662/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2663/// If so, returns true and places the converted type (that might differ from
2664/// ToType in its cv-qualifiers at some level) into ConvertedType.
2665bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002666 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002667 bool InOverloadResolution,
2668 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002669 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002670 if (!ToTypePtr)
2671 return false;
2672
2673 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002674 if (From->isNullPointerConstant(Context,
2675 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2676 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002677 ConvertedType = ToType;
2678 return true;
2679 }
2680
2681 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002682 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002683 if (!FromTypePtr)
2684 return false;
2685
2686 // A pointer to member of B can be converted to a pointer to member of D,
2687 // where D is derived from B (C++ 4.11p2).
2688 QualType FromClass(FromTypePtr->getClass(), 0);
2689 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002690
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002691 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002692 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002693 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002694 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2695 ToClass.getTypePtr());
2696 return true;
2697 }
2698
2699 return false;
2700}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002701
Sebastian Redl72b597d2009-01-25 19:43:20 +00002702/// CheckMemberPointerConversion - Check the member pointer conversion from the
2703/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002704/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002705/// for which IsMemberPointerConversion has already returned true. It returns
2706/// true and produces a diagnostic if there was an error, or returns false
2707/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002708bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002709 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002710 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002711 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002712 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002713 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002714 if (!FromPtrType) {
2715 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002716 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002717 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002718 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002719 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002720 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002721 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002722
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002723 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002724 assert(ToPtrType && "No member pointer cast has a target type "
2725 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002726
Sebastian Redled8f2002009-01-28 18:33:18 +00002727 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2728 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002729
Sebastian Redled8f2002009-01-28 18:33:18 +00002730 // FIXME: What about dependent types?
2731 assert(FromClass->isRecordType() && "Pointer into non-class.");
2732 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002733
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002734 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002735 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002736 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2737 assert(DerivationOkay &&
2738 "Should not have been called if derivation isn't OK.");
2739 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002740
Sebastian Redled8f2002009-01-28 18:33:18 +00002741 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2742 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002743 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2744 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2745 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2746 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002747 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002748
Douglas Gregor89ee6822009-02-28 01:32:25 +00002749 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002750 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2751 << FromClass << ToClass << QualType(VBase, 0)
2752 << From->getSourceRange();
2753 return true;
2754 }
2755
John McCall5b0829a2010-02-10 09:31:12 +00002756 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002757 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2758 Paths.front(),
2759 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002760
Anders Carlssond7923c62009-08-22 23:33:40 +00002761 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002762 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002763 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002764 return false;
2765}
2766
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002767/// Determine whether the lifetime conversion between the two given
2768/// qualifiers sets is nontrivial.
2769static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2770 Qualifiers ToQuals) {
2771 // Converting anything to const __unsafe_unretained is trivial.
2772 if (ToQuals.hasConst() &&
2773 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2774 return false;
2775
2776 return true;
2777}
2778
Douglas Gregor9a657932008-10-21 23:43:52 +00002779/// IsQualificationConversion - Determines whether the conversion from
2780/// an rvalue of type FromType to ToType is a qualification conversion
2781/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002782///
2783/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2784/// when the qualification conversion involves a change in the Objective-C
2785/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002786bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002787Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002788 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002789 FromType = Context.getCanonicalType(FromType);
2790 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002791 ObjCLifetimeConversion = false;
2792
Douglas Gregor9a657932008-10-21 23:43:52 +00002793 // If FromType and ToType are the same type, this is not a
2794 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002795 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002796 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002797
Douglas Gregor9a657932008-10-21 23:43:52 +00002798 // (C++ 4.4p4):
2799 // A conversion can add cv-qualifiers at levels other than the first
2800 // in multi-level pointers, subject to the following rules: [...]
2801 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002802 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002803 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002804 // Within each iteration of the loop, we check the qualifiers to
2805 // determine if this still looks like a qualification
2806 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002807 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002808 // until there are no more pointers or pointers-to-members left to
2809 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002810 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002811
Douglas Gregor90609aa2011-04-25 18:40:17 +00002812 Qualifiers FromQuals = FromType.getQualifiers();
2813 Qualifiers ToQuals = ToType.getQualifiers();
2814
John McCall31168b02011-06-15 23:02:42 +00002815 // Objective-C ARC:
2816 // Check Objective-C lifetime conversions.
2817 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2818 UnwrappedAnyPointer) {
2819 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002820 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2821 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002822 FromQuals.removeObjCLifetime();
2823 ToQuals.removeObjCLifetime();
2824 } else {
2825 // Qualification conversions cannot cast between different
2826 // Objective-C lifetime qualifiers.
2827 return false;
2828 }
2829 }
2830
Douglas Gregorf30053d2011-05-08 06:09:53 +00002831 // Allow addition/removal of GC attributes but not changing GC attributes.
2832 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2833 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2834 FromQuals.removeObjCGCAttr();
2835 ToQuals.removeObjCGCAttr();
2836 }
2837
Douglas Gregor9a657932008-10-21 23:43:52 +00002838 // -- for every j > 0, if const is in cv 1,j then const is in cv
2839 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002840 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002841 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002842
Douglas Gregor9a657932008-10-21 23:43:52 +00002843 // -- if the cv 1,j and cv 2,j are different, then const is in
2844 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002845 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002846 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002847 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002848
Douglas Gregor9a657932008-10-21 23:43:52 +00002849 // Keep track of whether all prior cv-qualifiers in the "to" type
2850 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002851 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002852 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002853 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002854
2855 // We are left with FromType and ToType being the pointee types
2856 // after unwrapping the original FromType and ToType the same number
2857 // of types. If we unwrapped any pointers, and if FromType and
2858 // ToType have the same unqualified type (since we checked
2859 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002860 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002861}
2862
Douglas Gregorc79862f2012-04-12 17:51:55 +00002863/// \brief - Determine whether this is a conversion from a scalar type to an
2864/// atomic type.
2865///
2866/// If successful, updates \c SCS's second and third steps in the conversion
2867/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002868static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2869 bool InOverloadResolution,
2870 StandardConversionSequence &SCS,
2871 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002872 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2873 if (!ToAtomic)
2874 return false;
2875
2876 StandardConversionSequence InnerSCS;
2877 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2878 InOverloadResolution, InnerSCS,
2879 CStyle, /*AllowObjCWritebackConversion=*/false))
2880 return false;
2881
2882 SCS.Second = InnerSCS.Second;
2883 SCS.setToType(1, InnerSCS.getToType(1));
2884 SCS.Third = InnerSCS.Third;
2885 SCS.QualificationIncludesObjCLifetime
2886 = InnerSCS.QualificationIncludesObjCLifetime;
2887 SCS.setToType(2, InnerSCS.getToType(2));
2888 return true;
2889}
2890
Sebastian Redle5417162012-03-27 18:33:03 +00002891static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2892 CXXConstructorDecl *Constructor,
2893 QualType Type) {
2894 const FunctionProtoType *CtorType =
2895 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002896 if (CtorType->getNumParams() > 0) {
2897 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002898 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2899 return true;
2900 }
2901 return false;
2902}
2903
Sebastian Redl82ace982012-02-11 23:51:08 +00002904static OverloadingResult
2905IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2906 CXXRecordDecl *To,
2907 UserDefinedConversionSequence &User,
2908 OverloadCandidateSet &CandidateSet,
2909 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002910 DeclContext::lookup_result R = S.LookupConstructors(To);
2911 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002912 Con != ConEnd; ++Con) {
2913 NamedDecl *D = *Con;
2914 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2915
2916 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00002917 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002918 FunctionTemplateDecl *ConstructorTmpl
2919 = dyn_cast<FunctionTemplateDecl>(D);
2920 if (ConstructorTmpl)
2921 Constructor
2922 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2923 else
2924 Constructor = cast<CXXConstructorDecl>(D);
2925
2926 bool Usable = !Constructor->isInvalidDecl() &&
2927 S.isInitListConstructor(Constructor) &&
2928 (AllowExplicit || !Constructor->isExplicit());
2929 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002930 // If the first argument is (a reference to) the target type,
2931 // suppress conversions.
2932 bool SuppressUserConversions =
2933 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002934 if (ConstructorTmpl)
2935 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00002936 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002937 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002938 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002939 else
2940 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002941 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002942 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002943 }
2944 }
2945
2946 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2947
2948 OverloadCandidateSet::iterator Best;
2949 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2950 case OR_Success: {
2951 // Record the standard conversion we used and the conversion function.
2952 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002953 QualType ThisType = Constructor->getThisType(S.Context);
2954 // Initializer lists don't have conversions as such.
2955 User.Before.setAsIdentityConversion();
2956 User.HadMultipleCandidates = HadMultipleCandidates;
2957 User.ConversionFunction = Constructor;
2958 User.FoundConversionFunction = Best->FoundDecl;
2959 User.After.setAsIdentityConversion();
2960 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2961 User.After.setAllToTypes(ToType);
2962 return OR_Success;
2963 }
2964
2965 case OR_No_Viable_Function:
2966 return OR_No_Viable_Function;
2967 case OR_Deleted:
2968 return OR_Deleted;
2969 case OR_Ambiguous:
2970 return OR_Ambiguous;
2971 }
2972
2973 llvm_unreachable("Invalid OverloadResult!");
2974}
2975
Douglas Gregor576e98c2009-01-30 23:27:23 +00002976/// Determines whether there is a user-defined conversion sequence
2977/// (C++ [over.ics.user]) that converts expression From to the type
2978/// ToType. If such a conversion exists, User will contain the
2979/// user-defined conversion sequence that performs such a conversion
2980/// and this routine will return true. Otherwise, this routine returns
2981/// false and User is unspecified.
2982///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002983/// \param AllowExplicit true if the conversion should consider C++0x
2984/// "explicit" conversion functions as well as non-explicit conversion
2985/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00002986///
2987/// \param AllowObjCConversionOnExplicit true if the conversion should
2988/// allow an extra Objective-C pointer conversion on uses of explicit
2989/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00002990static OverloadingResult
2991IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002992 UserDefinedConversionSequence &User,
2993 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00002994 bool AllowExplicit,
2995 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00002996 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00002997
Douglas Gregor5ab11652010-04-17 22:01:05 +00002998 // Whether we will only visit constructors.
2999 bool ConstructorsOnly = false;
3000
3001 // If the type we are conversion to is a class type, enumerate its
3002 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003003 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003004 // C++ [over.match.ctor]p1:
3005 // When objects of class type are direct-initialized (8.5), or
3006 // copy-initialized from an expression of the same or a
3007 // derived class type (8.5), overload resolution selects the
3008 // constructor. [...] For copy-initialization, the candidate
3009 // functions are all the converting constructors (12.3.1) of
3010 // that class. The argument list is the expression-list within
3011 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003012 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003013 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003014 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003015 ConstructorsOnly = true;
3016
Benjamin Kramer90633e32012-11-23 17:04:52 +00003017 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003018 // RequireCompleteType may have returned true due to some invalid decl
3019 // during template instantiation, but ToType may be complete enough now
3020 // to try to recover.
3021 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003022 // We're not going to find any constructors.
3023 } else if (CXXRecordDecl *ToRecordDecl
3024 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003025
3026 Expr **Args = &From;
3027 unsigned NumArgs = 1;
3028 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003029 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003030 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003031 OverloadingResult Result = IsInitializerListConstructorConversion(
3032 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3033 if (Result != OR_No_Viable_Function)
3034 return Result;
3035 // Never mind.
3036 CandidateSet.clear();
3037
3038 // If we're list-initializing, we pass the individual elements as
3039 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003040 Args = InitList->getInits();
3041 NumArgs = InitList->getNumInits();
3042 ListInitializing = true;
3043 }
3044
David Blaikieff7d47a2012-12-19 00:45:41 +00003045 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3046 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003047 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003048 NamedDecl *D = *Con;
3049 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3050
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003051 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003052 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003053 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003054 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003055 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003056 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003057 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3058 else
John McCalla0296f72010-03-19 07:35:19 +00003059 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003060
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003061 bool Usable = !Constructor->isInvalidDecl();
3062 if (ListInitializing)
3063 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3064 else
3065 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3066 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003067 bool SuppressUserConversions = !ConstructorsOnly;
3068 if (SuppressUserConversions && ListInitializing) {
3069 SuppressUserConversions = false;
3070 if (NumArgs == 1) {
3071 // If the first argument is (a reference to) the target type,
3072 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003073 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3074 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003075 }
3076 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003077 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003078 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003079 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003080 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003081 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003082 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003083 // Allow one user-defined conversion when user specifies a
3084 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003085 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003086 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003087 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003088 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003089 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003090 }
3091 }
3092
Douglas Gregor5ab11652010-04-17 22:01:05 +00003093 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003094 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003095 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003096 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003097 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003098 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003099 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003100 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3101 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003102 std::pair<CXXRecordDecl::conversion_iterator,
3103 CXXRecordDecl::conversion_iterator>
3104 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3105 for (CXXRecordDecl::conversion_iterator
3106 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003107 DeclAccessPair FoundDecl = I.getPair();
3108 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003109 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3110 if (isa<UsingShadowDecl>(D))
3111 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3112
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003113 CXXConversionDecl *Conv;
3114 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003115 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3116 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003117 else
John McCallda4458e2010-03-31 01:36:47 +00003118 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003119
3120 if (AllowExplicit || !Conv->isExplicit()) {
3121 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003122 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3123 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003124 CandidateSet,
3125 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003126 else
John McCall5c32be02010-08-24 20:38:10 +00003127 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003128 From, ToType, CandidateSet,
3129 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003130 }
3131 }
3132 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003133 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003134
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003135 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3136
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003137 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003138 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3139 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003140 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003141 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003142 // Record the standard conversion we used and the conversion function.
3143 if (CXXConstructorDecl *Constructor
3144 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3145 // C++ [over.ics.user]p1:
3146 // If the user-defined conversion is specified by a
3147 // constructor (12.3.1), the initial standard conversion
3148 // sequence converts the source type to the type required by
3149 // the argument of the constructor.
3150 //
3151 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003152 if (isa<InitListExpr>(From)) {
3153 // Initializer lists don't have conversions as such.
3154 User.Before.setAsIdentityConversion();
3155 } else {
3156 if (Best->Conversions[0].isEllipsis())
3157 User.EllipsisConversion = true;
3158 else {
3159 User.Before = Best->Conversions[0].Standard;
3160 User.EllipsisConversion = false;
3161 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003162 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003163 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003164 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003165 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003166 User.After.setAsIdentityConversion();
3167 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3168 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003169 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003170 }
3171 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003172 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3173 // C++ [over.ics.user]p1:
3174 //
3175 // [...] If the user-defined conversion is specified by a
3176 // conversion function (12.3.2), the initial standard
3177 // conversion sequence converts the source type to the
3178 // implicit object parameter of the conversion function.
3179 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003180 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003181 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003182 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003183 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003184
John McCall5c32be02010-08-24 20:38:10 +00003185 // C++ [over.ics.user]p2:
3186 // The second standard conversion sequence converts the
3187 // result of the user-defined conversion to the target type
3188 // for the sequence. Since an implicit conversion sequence
3189 // is an initialization, the special rules for
3190 // initialization by user-defined conversion apply when
3191 // selecting the best user-defined conversion for a
3192 // user-defined conversion sequence (see 13.3.3 and
3193 // 13.3.3.1).
3194 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003195 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003196 }
David Blaikie8a40f702012-01-17 06:56:22 +00003197 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003198
John McCall5c32be02010-08-24 20:38:10 +00003199 case OR_No_Viable_Function:
3200 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003201
John McCall5c32be02010-08-24 20:38:10 +00003202 case OR_Ambiguous:
3203 return OR_Ambiguous;
3204 }
3205
David Blaikie8a40f702012-01-17 06:56:22 +00003206 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003207}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003208
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003209bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003210Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003211 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003212 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3213 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003214 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003215 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003216 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003217 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003218 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3219 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003220 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003221 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003222 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003223 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003224 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3225 << From->getType() << From->getSourceRange() << ToType;
3226 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003227 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003228 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003229 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003230}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003231
Douglas Gregor2837aa22012-02-22 17:32:19 +00003232/// \brief Compare the user-defined conversion functions or constructors
3233/// of two user-defined conversion sequences to determine whether any ordering
3234/// is possible.
3235static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003236compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003237 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003238 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003239 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003240
Douglas Gregor2837aa22012-02-22 17:32:19 +00003241 // Objective-C++:
3242 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003243 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003244 // respectively, always prefer the conversion to a function pointer,
3245 // because the function pointer is more lightweight and is more likely
3246 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003247 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003248 if (!Conv1)
3249 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003250
Douglas Gregor2837aa22012-02-22 17:32:19 +00003251 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3252 if (!Conv2)
3253 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003254
Douglas Gregor2837aa22012-02-22 17:32:19 +00003255 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3256 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3257 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3258 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003259 return Block1 ? ImplicitConversionSequence::Worse
3260 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003261 }
3262
3263 return ImplicitConversionSequence::Indistinguishable;
3264}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003265
3266static bool hasDeprecatedStringLiteralToCharPtrConversion(
3267 const ImplicitConversionSequence &ICS) {
3268 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3269 (ICS.isUserDefined() &&
3270 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3271}
3272
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003273/// CompareImplicitConversionSequences - Compare two implicit
3274/// conversion sequences to determine whether one is better than the
3275/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003276static ImplicitConversionSequence::CompareKind
3277CompareImplicitConversionSequences(Sema &S,
3278 const ImplicitConversionSequence& ICS1,
3279 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003280{
3281 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3282 // conversion sequences (as defined in 13.3.3.1)
3283 // -- a standard conversion sequence (13.3.3.1.1) is a better
3284 // conversion sequence than a user-defined conversion sequence or
3285 // an ellipsis conversion sequence, and
3286 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3287 // conversion sequence than an ellipsis conversion sequence
3288 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003289 //
John McCall0d1da222010-01-12 00:44:57 +00003290 // C++0x [over.best.ics]p10:
3291 // For the purpose of ranking implicit conversion sequences as
3292 // described in 13.3.3.2, the ambiguous conversion sequence is
3293 // treated as a user-defined sequence that is indistinguishable
3294 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003295
3296 // String literal to 'char *' conversion has been deprecated in C++03. It has
3297 // been removed from C++11. We still accept this conversion, if it happens at
3298 // the best viable function. Otherwise, this conversion is considered worse
3299 // than ellipsis conversion. Consider this as an extension; this is not in the
3300 // standard. For example:
3301 //
3302 // int &f(...); // #1
3303 // void f(char*); // #2
3304 // void g() { int &r = f("foo"); }
3305 //
3306 // In C++03, we pick #2 as the best viable function.
3307 // In C++11, we pick #1 as the best viable function, because ellipsis
3308 // conversion is better than string-literal to char* conversion (since there
3309 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3310 // convert arguments, #2 would be the best viable function in C++11.
3311 // If the best viable function has this conversion, a warning will be issued
3312 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3313
3314 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3315 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3316 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3317 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3318 ? ImplicitConversionSequence::Worse
3319 : ImplicitConversionSequence::Better;
3320
Douglas Gregor5ab11652010-04-17 22:01:05 +00003321 if (ICS1.getKindRank() < ICS2.getKindRank())
3322 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003323 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003324 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003325
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003326 // The following checks require both conversion sequences to be of
3327 // the same kind.
3328 if (ICS1.getKind() != ICS2.getKind())
3329 return ImplicitConversionSequence::Indistinguishable;
3330
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003331 ImplicitConversionSequence::CompareKind Result =
3332 ImplicitConversionSequence::Indistinguishable;
3333
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003334 // Two implicit conversion sequences of the same form are
3335 // indistinguishable conversion sequences unless one of the
3336 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003337
3338 // List-initialization sequence L1 is a better conversion sequence than
3339 // list-initialization sequence L2 if:
3340 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3341 // if not that,
3342 // - L1 converts to type “array of N1 T”, L2 converts to type “array of N2 T”,
3343 // and N1 is smaller than N2.,
3344 // even if one of the other rules in this paragraph would otherwise apply.
3345 if (!ICS1.isBad()) {
3346 if (ICS1.isStdInitializerListElement() &&
3347 !ICS2.isStdInitializerListElement())
3348 return ImplicitConversionSequence::Better;
3349 if (!ICS1.isStdInitializerListElement() &&
3350 ICS2.isStdInitializerListElement())
3351 return ImplicitConversionSequence::Worse;
3352 }
3353
John McCall0d1da222010-01-12 00:44:57 +00003354 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003355 // Standard conversion sequence S1 is a better conversion sequence than
3356 // standard conversion sequence S2 if [...]
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003357 Result = CompareStandardConversionSequences(S,
3358 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003359 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003360 // User-defined conversion sequence U1 is a better conversion
3361 // sequence than another user-defined conversion sequence U2 if
3362 // they contain the same user-defined conversion function or
3363 // constructor and if the second standard conversion sequence of
3364 // U1 is better than the second standard conversion sequence of
3365 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003366 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003367 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003368 Result = CompareStandardConversionSequences(S,
3369 ICS1.UserDefined.After,
3370 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003371 else
3372 Result = compareConversionFunctions(S,
3373 ICS1.UserDefined.ConversionFunction,
3374 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003375 }
3376
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003377 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003378}
3379
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003380static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3381 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3382 Qualifiers Quals;
3383 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003385 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003386
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003387 return Context.hasSameUnqualifiedType(T1, T2);
3388}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003389
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003390// Per 13.3.3.2p3, compare the given standard conversion sequences to
3391// determine if one is a proper subset of the other.
3392static ImplicitConversionSequence::CompareKind
3393compareStandardConversionSubsets(ASTContext &Context,
3394 const StandardConversionSequence& SCS1,
3395 const StandardConversionSequence& SCS2) {
3396 ImplicitConversionSequence::CompareKind Result
3397 = ImplicitConversionSequence::Indistinguishable;
3398
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003399 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003400 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003401 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3402 return ImplicitConversionSequence::Better;
3403 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3404 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003405
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003406 if (SCS1.Second != SCS2.Second) {
3407 if (SCS1.Second == ICK_Identity)
3408 Result = ImplicitConversionSequence::Better;
3409 else if (SCS2.Second == ICK_Identity)
3410 Result = ImplicitConversionSequence::Worse;
3411 else
3412 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003413 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003414 return ImplicitConversionSequence::Indistinguishable;
3415
3416 if (SCS1.Third == SCS2.Third) {
3417 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3418 : ImplicitConversionSequence::Indistinguishable;
3419 }
3420
3421 if (SCS1.Third == ICK_Identity)
3422 return Result == ImplicitConversionSequence::Worse
3423 ? ImplicitConversionSequence::Indistinguishable
3424 : ImplicitConversionSequence::Better;
3425
3426 if (SCS2.Third == ICK_Identity)
3427 return Result == ImplicitConversionSequence::Better
3428 ? ImplicitConversionSequence::Indistinguishable
3429 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003430
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003431 return ImplicitConversionSequence::Indistinguishable;
3432}
3433
Douglas Gregore696ebb2011-01-26 14:52:12 +00003434/// \brief Determine whether one of the given reference bindings is better
3435/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003436static bool
3437isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3438 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003439 // C++0x [over.ics.rank]p3b4:
3440 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3441 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003443 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003444 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003445 // reference*.
3446 //
3447 // FIXME: Rvalue references. We're going rogue with the above edits,
3448 // because the semantics in the current C++0x working paper (N3225 at the
3449 // time of this writing) break the standard definition of std::forward
3450 // and std::reference_wrapper when dealing with references to functions.
3451 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003452 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3453 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3454 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003455
Douglas Gregore696ebb2011-01-26 14:52:12 +00003456 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3457 SCS2.IsLvalueReference) ||
3458 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003459 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003460}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003461
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003462/// CompareStandardConversionSequences - Compare two standard
3463/// conversion sequences to determine whether one is better than the
3464/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003465static ImplicitConversionSequence::CompareKind
3466CompareStandardConversionSequences(Sema &S,
3467 const StandardConversionSequence& SCS1,
3468 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003469{
3470 // Standard conversion sequence S1 is a better conversion sequence
3471 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3472
3473 // -- S1 is a proper subsequence of S2 (comparing the conversion
3474 // sequences in the canonical form defined by 13.3.3.1.1,
3475 // excluding any Lvalue Transformation; the identity conversion
3476 // sequence is considered to be a subsequence of any
3477 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003478 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003479 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003480 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003481
3482 // -- the rank of S1 is better than the rank of S2 (by the rules
3483 // defined below), or, if not that,
3484 ImplicitConversionRank Rank1 = SCS1.getRank();
3485 ImplicitConversionRank Rank2 = SCS2.getRank();
3486 if (Rank1 < Rank2)
3487 return ImplicitConversionSequence::Better;
3488 else if (Rank2 < Rank1)
3489 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003490
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003491 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3492 // are indistinguishable unless one of the following rules
3493 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003494
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003495 // A conversion that is not a conversion of a pointer, or
3496 // pointer to member, to bool is better than another conversion
3497 // that is such a conversion.
3498 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3499 return SCS2.isPointerConversionToBool()
3500 ? ImplicitConversionSequence::Better
3501 : ImplicitConversionSequence::Worse;
3502
Douglas Gregor5c407d92008-10-23 00:40:37 +00003503 // C++ [over.ics.rank]p4b2:
3504 //
3505 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003506 // conversion of B* to A* is better than conversion of B* to
3507 // void*, and conversion of A* to void* is better than conversion
3508 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003509 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003510 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003511 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003512 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003513 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3514 // Exactly one of the conversion sequences is a conversion to
3515 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003516 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3517 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003518 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3519 // Neither conversion sequence converts to a void pointer; compare
3520 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003521 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003522 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003523 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003524 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3525 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003526 // Both conversion sequences are conversions to void
3527 // pointers. Compare the source types to determine if there's an
3528 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003529 QualType FromType1 = SCS1.getFromType();
3530 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003531
3532 // Adjust the types we're converting from via the array-to-pointer
3533 // conversion, if we need to.
3534 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003535 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003536 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003537 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003538
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003539 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3540 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003541
John McCall5c32be02010-08-24 20:38:10 +00003542 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003543 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003544 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003545 return ImplicitConversionSequence::Worse;
3546
3547 // Objective-C++: If one interface is more specific than the
3548 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003549 const ObjCObjectPointerType* FromObjCPtr1
3550 = FromType1->getAs<ObjCObjectPointerType>();
3551 const ObjCObjectPointerType* FromObjCPtr2
3552 = FromType2->getAs<ObjCObjectPointerType>();
3553 if (FromObjCPtr1 && FromObjCPtr2) {
3554 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3555 FromObjCPtr2);
3556 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3557 FromObjCPtr1);
3558 if (AssignLeft != AssignRight) {
3559 return AssignLeft? ImplicitConversionSequence::Better
3560 : ImplicitConversionSequence::Worse;
3561 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003562 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003563 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003564
3565 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3566 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003567 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003568 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003569 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003570
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003571 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003572 // Check for a better reference binding based on the kind of bindings.
3573 if (isBetterReferenceBindingKind(SCS1, SCS2))
3574 return ImplicitConversionSequence::Better;
3575 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3576 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003577
Sebastian Redlb28b4072009-03-22 23:49:27 +00003578 // C++ [over.ics.rank]p3b4:
3579 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3580 // which the references refer are the same type except for
3581 // top-level cv-qualifiers, and the type to which the reference
3582 // initialized by S2 refers is more cv-qualified than the type
3583 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003584 QualType T1 = SCS1.getToType(2);
3585 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003586 T1 = S.Context.getCanonicalType(T1);
3587 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003588 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003589 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3590 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003591 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003592 // Objective-C++ ARC: If the references refer to objects with different
3593 // lifetimes, prefer bindings that don't change lifetime.
3594 if (SCS1.ObjCLifetimeConversionBinding !=
3595 SCS2.ObjCLifetimeConversionBinding) {
3596 return SCS1.ObjCLifetimeConversionBinding
3597 ? ImplicitConversionSequence::Worse
3598 : ImplicitConversionSequence::Better;
3599 }
3600
Chandler Carruth8e543b32010-12-12 08:17:55 +00003601 // If the type is an array type, promote the element qualifiers to the
3602 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003603 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003604 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003605 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003606 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003607 if (T2.isMoreQualifiedThan(T1))
3608 return ImplicitConversionSequence::Better;
3609 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003610 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003611 }
3612 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003613
Francois Pichet08d2fa02011-09-18 21:37:37 +00003614 // In Microsoft mode, prefer an integral conversion to a
3615 // floating-to-integral conversion if the integral conversion
3616 // is between types of the same size.
3617 // For example:
3618 // void f(float);
3619 // void f(int);
3620 // int main {
3621 // long a;
3622 // f(a);
3623 // }
3624 // Here, MSVC will call f(int) instead of generating a compile error
3625 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003626 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3627 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003628 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003629 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003630 return ImplicitConversionSequence::Better;
3631
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003632 return ImplicitConversionSequence::Indistinguishable;
3633}
3634
3635/// CompareQualificationConversions - Compares two standard conversion
3636/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003637/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003638static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003639CompareQualificationConversions(Sema &S,
3640 const StandardConversionSequence& SCS1,
3641 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003642 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003643 // -- S1 and S2 differ only in their qualification conversion and
3644 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3645 // cv-qualification signature of type T1 is a proper subset of
3646 // the cv-qualification signature of type T2, and S1 is not the
3647 // deprecated string literal array-to-pointer conversion (4.2).
3648 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3649 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3650 return ImplicitConversionSequence::Indistinguishable;
3651
3652 // FIXME: the example in the standard doesn't use a qualification
3653 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003654 QualType T1 = SCS1.getToType(2);
3655 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003656 T1 = S.Context.getCanonicalType(T1);
3657 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003658 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003659 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3660 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003661
3662 // If the types are the same, we won't learn anything by unwrapped
3663 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003664 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003665 return ImplicitConversionSequence::Indistinguishable;
3666
Chandler Carruth607f38e2009-12-29 07:16:59 +00003667 // If the type is an array type, promote the element qualifiers to the type
3668 // for comparison.
3669 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003670 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003671 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003672 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003673
Mike Stump11289f42009-09-09 15:08:12 +00003674 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003675 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003676
3677 // Objective-C++ ARC:
3678 // Prefer qualification conversions not involving a change in lifetime
3679 // to qualification conversions that do not change lifetime.
3680 if (SCS1.QualificationIncludesObjCLifetime !=
3681 SCS2.QualificationIncludesObjCLifetime) {
3682 Result = SCS1.QualificationIncludesObjCLifetime
3683 ? ImplicitConversionSequence::Worse
3684 : ImplicitConversionSequence::Better;
3685 }
3686
John McCall5c32be02010-08-24 20:38:10 +00003687 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003688 // Within each iteration of the loop, we check the qualifiers to
3689 // determine if this still looks like a qualification
3690 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003691 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003692 // until there are no more pointers or pointers-to-members left
3693 // to unwrap. This essentially mimics what
3694 // IsQualificationConversion does, but here we're checking for a
3695 // strict subset of qualifiers.
3696 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3697 // The qualifiers are the same, so this doesn't tell us anything
3698 // about how the sequences rank.
3699 ;
3700 else if (T2.isMoreQualifiedThan(T1)) {
3701 // T1 has fewer qualifiers, so it could be the better sequence.
3702 if (Result == ImplicitConversionSequence::Worse)
3703 // Neither has qualifiers that are a subset of the other's
3704 // qualifiers.
3705 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003706
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003707 Result = ImplicitConversionSequence::Better;
3708 } else if (T1.isMoreQualifiedThan(T2)) {
3709 // T2 has fewer qualifiers, so it could be the better sequence.
3710 if (Result == ImplicitConversionSequence::Better)
3711 // Neither has qualifiers that are a subset of the other's
3712 // qualifiers.
3713 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003714
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003715 Result = ImplicitConversionSequence::Worse;
3716 } else {
3717 // Qualifiers are disjoint.
3718 return ImplicitConversionSequence::Indistinguishable;
3719 }
3720
3721 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003722 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003723 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003724 }
3725
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003726 // Check that the winning standard conversion sequence isn't using
3727 // the deprecated string literal array to pointer conversion.
3728 switch (Result) {
3729 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003730 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003731 Result = ImplicitConversionSequence::Indistinguishable;
3732 break;
3733
3734 case ImplicitConversionSequence::Indistinguishable:
3735 break;
3736
3737 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003738 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003739 Result = ImplicitConversionSequence::Indistinguishable;
3740 break;
3741 }
3742
3743 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003744}
3745
Douglas Gregor5c407d92008-10-23 00:40:37 +00003746/// CompareDerivedToBaseConversions - Compares two standard conversion
3747/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003748/// various kinds of derived-to-base conversions (C++
3749/// [over.ics.rank]p4b3). As part of these checks, we also look at
3750/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003751static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003752CompareDerivedToBaseConversions(Sema &S,
3753 const StandardConversionSequence& SCS1,
3754 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003755 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003756 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003757 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003758 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003759
3760 // Adjust the types we're converting from via the array-to-pointer
3761 // conversion, if we need to.
3762 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003763 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003764 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003765 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003766
3767 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003768 FromType1 = S.Context.getCanonicalType(FromType1);
3769 ToType1 = S.Context.getCanonicalType(ToType1);
3770 FromType2 = S.Context.getCanonicalType(FromType2);
3771 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003772
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003773 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003774 //
3775 // If class B is derived directly or indirectly from class A and
3776 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003777 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003778 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003779 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003780 SCS2.Second == ICK_Pointer_Conversion &&
3781 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3782 FromType1->isPointerType() && FromType2->isPointerType() &&
3783 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003784 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003785 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003786 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003787 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003788 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003789 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003790 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003791 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003792
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003793 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003794 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003795 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003796 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003797 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003798 return ImplicitConversionSequence::Worse;
3799 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003800
3801 // -- conversion of B* to A* is better than conversion of C* to A*,
3802 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003803 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003804 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003805 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003806 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003807 }
3808 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3809 SCS2.Second == ICK_Pointer_Conversion) {
3810 const ObjCObjectPointerType *FromPtr1
3811 = FromType1->getAs<ObjCObjectPointerType>();
3812 const ObjCObjectPointerType *FromPtr2
3813 = FromType2->getAs<ObjCObjectPointerType>();
3814 const ObjCObjectPointerType *ToPtr1
3815 = ToType1->getAs<ObjCObjectPointerType>();
3816 const ObjCObjectPointerType *ToPtr2
3817 = ToType2->getAs<ObjCObjectPointerType>();
3818
3819 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3820 // Apply the same conversion ranking rules for Objective-C pointer types
3821 // that we do for C++ pointers to class types. However, we employ the
3822 // Objective-C pseudo-subtyping relationship used for assignment of
3823 // Objective-C pointer types.
3824 bool FromAssignLeft
3825 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3826 bool FromAssignRight
3827 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3828 bool ToAssignLeft
3829 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3830 bool ToAssignRight
3831 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3832
3833 // A conversion to an a non-id object pointer type or qualified 'id'
3834 // type is better than a conversion to 'id'.
3835 if (ToPtr1->isObjCIdType() &&
3836 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3837 return ImplicitConversionSequence::Worse;
3838 if (ToPtr2->isObjCIdType() &&
3839 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3840 return ImplicitConversionSequence::Better;
3841
3842 // A conversion to a non-id object pointer type is better than a
3843 // conversion to a qualified 'id' type
3844 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3845 return ImplicitConversionSequence::Worse;
3846 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3847 return ImplicitConversionSequence::Better;
3848
3849 // A conversion to an a non-Class object pointer type or qualified 'Class'
3850 // type is better than a conversion to 'Class'.
3851 if (ToPtr1->isObjCClassType() &&
3852 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3853 return ImplicitConversionSequence::Worse;
3854 if (ToPtr2->isObjCClassType() &&
3855 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3856 return ImplicitConversionSequence::Better;
3857
3858 // A conversion to a non-Class object pointer type is better than a
3859 // conversion to a qualified 'Class' type.
3860 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3861 return ImplicitConversionSequence::Worse;
3862 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3863 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003864
Douglas Gregor058d3de2011-01-31 18:51:41 +00003865 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3866 if (S.Context.hasSameType(FromType1, FromType2) &&
3867 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3868 (ToAssignLeft != ToAssignRight))
3869 return ToAssignLeft? ImplicitConversionSequence::Worse
3870 : ImplicitConversionSequence::Better;
3871
3872 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3873 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3874 (FromAssignLeft != FromAssignRight))
3875 return FromAssignLeft? ImplicitConversionSequence::Better
3876 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003877 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003878 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003879
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003880 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003881 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3882 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3883 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003884 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003885 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003886 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003887 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003888 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003889 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003890 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003891 ToType2->getAs<MemberPointerType>();
3892 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3893 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3894 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3895 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3896 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3897 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3898 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3899 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003900 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003901 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003902 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003903 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003904 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003905 return ImplicitConversionSequence::Better;
3906 }
3907 // conversion of B::* to C::* is better than conversion of A::* to C::*
3908 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003909 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003910 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003911 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003912 return ImplicitConversionSequence::Worse;
3913 }
3914 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003915
Douglas Gregor5ab11652010-04-17 22:01:05 +00003916 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003917 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003918 // -- binding of an expression of type C to a reference of type
3919 // B& is better than binding an expression of type C to a
3920 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003921 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3922 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3923 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003924 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003925 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003926 return ImplicitConversionSequence::Worse;
3927 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003928
Douglas Gregor2fe98832008-11-03 19:09:14 +00003929 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003930 // -- binding of an expression of type B to a reference of type
3931 // A& is better than binding an expression of type C to a
3932 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003933 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3934 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3935 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003936 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003937 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003938 return ImplicitConversionSequence::Worse;
3939 }
3940 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003941
Douglas Gregor5c407d92008-10-23 00:40:37 +00003942 return ImplicitConversionSequence::Indistinguishable;
3943}
3944
Douglas Gregor45bb4832013-03-26 23:36:30 +00003945/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3946/// C++ class.
3947static bool isTypeValid(QualType T) {
3948 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3949 return !Record->isInvalidDecl();
3950
3951 return true;
3952}
3953
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003954/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3955/// determine whether they are reference-related,
3956/// reference-compatible, reference-compatible with added
3957/// qualification, or incompatible, for use in C++ initialization by
3958/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3959/// type, and the first type (T1) is the pointee type of the reference
3960/// type being initialized.
3961Sema::ReferenceCompareResult
3962Sema::CompareReferenceRelationship(SourceLocation Loc,
3963 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003964 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003965 bool &ObjCConversion,
3966 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003967 assert(!OrigT1->isReferenceType() &&
3968 "T1 must be the pointee type of the reference type");
3969 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3970
3971 QualType T1 = Context.getCanonicalType(OrigT1);
3972 QualType T2 = Context.getCanonicalType(OrigT2);
3973 Qualifiers T1Quals, T2Quals;
3974 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3975 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3976
3977 // C++ [dcl.init.ref]p4:
3978 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3979 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3980 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003981 DerivedToBase = false;
3982 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003983 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003984 if (UnqualT1 == UnqualT2) {
3985 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003986 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00003987 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3988 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003989 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003990 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3991 UnqualT2->isObjCObjectOrInterfaceType() &&
3992 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3993 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003994 else
3995 return Ref_Incompatible;
3996
3997 // At this point, we know that T1 and T2 are reference-related (at
3998 // least).
3999
4000 // If the type is an array type, promote the element qualifiers to the type
4001 // for comparison.
4002 if (isa<ArrayType>(T1) && T1Quals)
4003 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4004 if (isa<ArrayType>(T2) && T2Quals)
4005 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4006
4007 // C++ [dcl.init.ref]p4:
4008 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4009 // reference-related to T2 and cv1 is the same cv-qualification
4010 // as, or greater cv-qualification than, cv2. For purposes of
4011 // overload resolution, cases for which cv1 is greater
4012 // cv-qualification than cv2 are identified as
4013 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004014 //
4015 // Note that we also require equivalence of Objective-C GC and address-space
4016 // qualifiers when performing these computations, so that e.g., an int in
4017 // address space 1 is not reference-compatible with an int in address
4018 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004019 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4020 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004021 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4022 ObjCLifetimeConversion = true;
4023
John McCall31168b02011-06-15 23:02:42 +00004024 T1Quals.removeObjCLifetime();
4025 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004026 }
4027
Douglas Gregord517d552011-04-28 17:56:11 +00004028 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004029 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004030 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004031 return Ref_Compatible_With_Added_Qualification;
4032 else
4033 return Ref_Related;
4034}
4035
Douglas Gregor836a7e82010-08-11 02:15:33 +00004036/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004037/// with DeclType. Return true if something definite is found.
4038static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004039FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4040 QualType DeclType, SourceLocation DeclLoc,
4041 Expr *Init, QualType T2, bool AllowRvalues,
4042 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004043 assert(T2->isRecordType() && "Can only find conversions of record types.");
4044 CXXRecordDecl *T2RecordDecl
4045 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4046
Richard Smith100b24a2014-04-17 01:52:14 +00004047 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004048 std::pair<CXXRecordDecl::conversion_iterator,
4049 CXXRecordDecl::conversion_iterator>
4050 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4051 for (CXXRecordDecl::conversion_iterator
4052 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004053 NamedDecl *D = *I;
4054 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4055 if (isa<UsingShadowDecl>(D))
4056 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4057
4058 FunctionTemplateDecl *ConvTemplate
4059 = dyn_cast<FunctionTemplateDecl>(D);
4060 CXXConversionDecl *Conv;
4061 if (ConvTemplate)
4062 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4063 else
4064 Conv = cast<CXXConversionDecl>(D);
4065
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004066 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004067 // explicit conversions, skip it.
4068 if (!AllowExplicit && Conv->isExplicit())
4069 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004070
Douglas Gregor836a7e82010-08-11 02:15:33 +00004071 if (AllowRvalues) {
4072 bool DerivedToBase = false;
4073 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004074 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004075
4076 // If we are initializing an rvalue reference, don't permit conversion
4077 // functions that return lvalues.
4078 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4079 const ReferenceType *RefType
4080 = Conv->getConversionType()->getAs<LValueReferenceType>();
4081 if (RefType && !RefType->getPointeeType()->isFunctionType())
4082 continue;
4083 }
4084
Douglas Gregor836a7e82010-08-11 02:15:33 +00004085 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004086 S.CompareReferenceRelationship(
4087 DeclLoc,
4088 Conv->getConversionType().getNonReferenceType()
4089 .getUnqualifiedType(),
4090 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004091 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004092 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004093 continue;
4094 } else {
4095 // If the conversion function doesn't return a reference type,
4096 // it can't be considered for this conversion. An rvalue reference
4097 // is only acceptable if its referencee is a function type.
4098
4099 const ReferenceType *RefType =
4100 Conv->getConversionType()->getAs<ReferenceType>();
4101 if (!RefType ||
4102 (!RefType->isLValueReferenceType() &&
4103 !RefType->getPointeeType()->isFunctionType()))
4104 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004106
Douglas Gregor836a7e82010-08-11 02:15:33 +00004107 if (ConvTemplate)
4108 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004109 Init, DeclType, CandidateSet,
4110 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004111 else
4112 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004113 DeclType, CandidateSet,
4114 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004115 }
4116
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004117 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4118
Sebastian Redld92badf2010-06-30 18:13:39 +00004119 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004120 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004121 case OR_Success:
4122 // C++ [over.ics.ref]p1:
4123 //
4124 // [...] If the parameter binds directly to the result of
4125 // applying a conversion function to the argument
4126 // expression, the implicit conversion sequence is a
4127 // user-defined conversion sequence (13.3.3.1.2), with the
4128 // second standard conversion sequence either an identity
4129 // conversion or, if the conversion function returns an
4130 // entity of a type that is a derived class of the parameter
4131 // type, a derived-to-base Conversion.
4132 if (!Best->FinalConversion.DirectBinding)
4133 return false;
4134
4135 ICS.setUserDefined();
4136 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4137 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004138 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004139 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004140 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004141 ICS.UserDefined.EllipsisConversion = false;
4142 assert(ICS.UserDefined.After.ReferenceBinding &&
4143 ICS.UserDefined.After.DirectBinding &&
4144 "Expected a direct reference binding!");
4145 return true;
4146
4147 case OR_Ambiguous:
4148 ICS.setAmbiguous();
4149 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4150 Cand != CandidateSet.end(); ++Cand)
4151 if (Cand->Viable)
4152 ICS.Ambiguous.addConversion(Cand->Function);
4153 return true;
4154
4155 case OR_No_Viable_Function:
4156 case OR_Deleted:
4157 // There was no suitable conversion, or we found a deleted
4158 // conversion; continue with other checks.
4159 return false;
4160 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004161
David Blaikie8a40f702012-01-17 06:56:22 +00004162 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004163}
4164
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004165/// \brief Compute an implicit conversion sequence for reference
4166/// initialization.
4167static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004168TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004169 SourceLocation DeclLoc,
4170 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004171 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004172 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4173
4174 // Most paths end in a failed conversion.
4175 ImplicitConversionSequence ICS;
4176 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4177
4178 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4179 QualType T2 = Init->getType();
4180
4181 // If the initializer is the address of an overloaded function, try
4182 // to resolve the overloaded function. If all goes well, T2 is the
4183 // type of the resulting function.
4184 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4185 DeclAccessPair Found;
4186 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4187 false, Found))
4188 T2 = Fn->getType();
4189 }
4190
4191 // Compute some basic properties of the types and the initializer.
4192 bool isRValRef = DeclType->isRValueReferenceType();
4193 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004194 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004195 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004196 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004197 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004198 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004199 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004200
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004201
Sebastian Redld92badf2010-06-30 18:13:39 +00004202 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004203 // A reference to type "cv1 T1" is initialized by an expression
4204 // of type "cv2 T2" as follows:
4205
Sebastian Redld92badf2010-06-30 18:13:39 +00004206 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004207 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004208 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4209 // reference-compatible with "cv2 T2," or
4210 //
4211 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4212 if (InitCategory.isLValue() &&
4213 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004214 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004215 // When a parameter of reference type binds directly (8.5.3)
4216 // to an argument expression, the implicit conversion sequence
4217 // is the identity conversion, unless the argument expression
4218 // has a type that is a derived class of the parameter type,
4219 // in which case the implicit conversion sequence is a
4220 // derived-to-base Conversion (13.3.3.1).
4221 ICS.setStandard();
4222 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004223 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4224 : ObjCConversion? ICK_Compatible_Conversion
4225 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004226 ICS.Standard.Third = ICK_Identity;
4227 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4228 ICS.Standard.setToType(0, T2);
4229 ICS.Standard.setToType(1, T1);
4230 ICS.Standard.setToType(2, T1);
4231 ICS.Standard.ReferenceBinding = true;
4232 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004233 ICS.Standard.IsLvalueReference = !isRValRef;
4234 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4235 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004236 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004237 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004238 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004239 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004240
Sebastian Redld92badf2010-06-30 18:13:39 +00004241 // Nothing more to do: the inaccessibility/ambiguity check for
4242 // derived-to-base conversions is suppressed when we're
4243 // computing the implicit conversion sequence (C++
4244 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004245 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004246 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004247
Sebastian Redld92badf2010-06-30 18:13:39 +00004248 // -- has a class type (i.e., T2 is a class type), where T1 is
4249 // not reference-related to T2, and can be implicitly
4250 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4251 // is reference-compatible with "cv3 T3" 92) (this
4252 // conversion is selected by enumerating the applicable
4253 // conversion functions (13.3.1.6) and choosing the best
4254 // one through overload resolution (13.3)),
4255 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004256 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004257 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004258 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4259 Init, T2, /*AllowRvalues=*/false,
4260 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004261 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004262 }
4263 }
4264
Sebastian Redld92badf2010-06-30 18:13:39 +00004265 // -- Otherwise, the reference shall be an lvalue reference to a
4266 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004267 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004268 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004269 return ICS;
4270
Douglas Gregorf143cd52011-01-24 16:14:37 +00004271 // -- If the initializer expression
4272 //
4273 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004274 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004275 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4276 (InitCategory.isXValue() ||
4277 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4278 (InitCategory.isLValue() && T2->isFunctionType()))) {
4279 ICS.setStandard();
4280 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004281 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004282 : ObjCConversion? ICK_Compatible_Conversion
4283 : ICK_Identity;
4284 ICS.Standard.Third = ICK_Identity;
4285 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4286 ICS.Standard.setToType(0, T2);
4287 ICS.Standard.setToType(1, T1);
4288 ICS.Standard.setToType(2, T1);
4289 ICS.Standard.ReferenceBinding = true;
4290 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4291 // binding unless we're binding to a class prvalue.
4292 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4293 // allow the use of rvalue references in C++98/03 for the benefit of
4294 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004295 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004296 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004297 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004298 ICS.Standard.IsLvalueReference = !isRValRef;
4299 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004300 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004301 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004302 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004303 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004304 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004305 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307
Douglas Gregorf143cd52011-01-24 16:14:37 +00004308 // -- has a class type (i.e., T2 is a class type), where T1 is not
4309 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310 // an xvalue, class prvalue, or function lvalue of type
4311 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004312 // "cv3 T3",
4313 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004315 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004316 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004317 // class subobject).
4318 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004320 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4321 Init, T2, /*AllowRvalues=*/true,
4322 AllowExplicit)) {
4323 // In the second case, if the reference is an rvalue reference
4324 // and the second standard conversion sequence of the
4325 // user-defined conversion sequence includes an lvalue-to-rvalue
4326 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004328 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4329 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4330
Douglas Gregor95273c32011-01-21 16:36:05 +00004331 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004332 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004333
Richard Smith19172c42014-07-14 02:28:44 +00004334 // A temporary of function type cannot be created; don't even try.
4335 if (T1->isFunctionType())
4336 return ICS;
4337
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004338 // -- Otherwise, a temporary of type "cv1 T1" is created and
4339 // initialized from the initializer expression using the
4340 // rules for a non-reference copy initialization (8.5). The
4341 // reference is then bound to the temporary. If T1 is
4342 // reference-related to T2, cv1 must be the same
4343 // cv-qualification as, or greater cv-qualification than,
4344 // cv2; otherwise, the program is ill-formed.
4345 if (RefRelationship == Sema::Ref_Related) {
4346 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4347 // we would be reference-compatible or reference-compatible with
4348 // added qualification. But that wasn't the case, so the reference
4349 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004350 //
4351 // Note that we only want to check address spaces and cvr-qualifiers here.
4352 // ObjC GC and lifetime qualifiers aren't important.
4353 Qualifiers T1Quals = T1.getQualifiers();
4354 Qualifiers T2Quals = T2.getQualifiers();
4355 T1Quals.removeObjCGCAttr();
4356 T1Quals.removeObjCLifetime();
4357 T2Quals.removeObjCGCAttr();
4358 T2Quals.removeObjCLifetime();
4359 if (!T1Quals.compatiblyIncludes(T2Quals))
4360 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004361 }
4362
4363 // If at least one of the types is a class type, the types are not
4364 // related, and we aren't allowed any user conversions, the
4365 // reference binding fails. This case is important for breaking
4366 // recursion, since TryImplicitConversion below will attempt to
4367 // create a temporary through the use of a copy constructor.
4368 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4369 (T1->isRecordType() || T2->isRecordType()))
4370 return ICS;
4371
Douglas Gregorcba72b12011-01-21 05:18:22 +00004372 // If T1 is reference-related to T2 and the reference is an rvalue
4373 // reference, the initializer expression shall not be an lvalue.
4374 if (RefRelationship >= Sema::Ref_Related &&
4375 isRValRef && Init->Classify(S.Context).isLValue())
4376 return ICS;
4377
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004378 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004379 // When a parameter of reference type is not bound directly to
4380 // an argument expression, the conversion sequence is the one
4381 // required to convert the argument expression to the
4382 // underlying type of the reference according to
4383 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4384 // to copy-initializing a temporary of the underlying type with
4385 // the argument expression. Any difference in top-level
4386 // cv-qualification is subsumed by the initialization itself
4387 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004388 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4389 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004390 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004391 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004392 /*AllowObjCWritebackConversion=*/false,
4393 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004394
4395 // Of course, that's still a reference binding.
4396 if (ICS.isStandard()) {
4397 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004398 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004399 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004400 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004401 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004402 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004403 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004404 const ReferenceType *LValRefType =
4405 ICS.UserDefined.ConversionFunction->getReturnType()
4406 ->getAs<LValueReferenceType>();
4407
4408 // C++ [over.ics.ref]p3:
4409 // Except for an implicit object parameter, for which see 13.3.1, a
4410 // standard conversion sequence cannot be formed if it requires [...]
4411 // binding an rvalue reference to an lvalue other than a function
4412 // lvalue.
4413 // Note that the function case is not possible here.
4414 if (DeclType->isRValueReferenceType() && LValRefType) {
4415 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4416 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4417 // reference to an rvalue!
4418 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4419 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004420 }
Richard Smith19172c42014-07-14 02:28:44 +00004421
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004422 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004423 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004424 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004425 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4426 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004427 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4428 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004429 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004430
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004431 return ICS;
4432}
4433
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004434static ImplicitConversionSequence
4435TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4436 bool SuppressUserConversions,
4437 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004438 bool AllowObjCWritebackConversion,
4439 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004440
4441/// TryListConversion - Try to copy-initialize a value of type ToType from the
4442/// initializer list From.
4443static ImplicitConversionSequence
4444TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4445 bool SuppressUserConversions,
4446 bool InOverloadResolution,
4447 bool AllowObjCWritebackConversion) {
4448 // C++11 [over.ics.list]p1:
4449 // When an argument is an initializer list, it is not an expression and
4450 // special rules apply for converting it to a parameter type.
4451
4452 ImplicitConversionSequence Result;
4453 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4454
Sebastian Redl09edce02012-01-23 22:09:39 +00004455 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004456 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004457 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004458 return Result;
4459
Larisse Voufo19d08672015-01-27 18:47:05 +00004460 // Per DR1467:
4461 // If the parameter type is a class X and the initializer list has a single
4462 // element of type cv U, where U is X or a class derived from X, the
4463 // implicit conversion sequence is the one required to convert the element
4464 // to the parameter type.
4465 //
4466 // Otherwise, if the parameter type is a character array [... ]
4467 // and the initializer list has a single element that is an
4468 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4469 // implicit conversion sequence is the identity conversion.
4470 if (From->getNumInits() == 1) {
4471 if (ToType->isRecordType()) {
4472 QualType InitType = From->getInit(0)->getType();
4473 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4474 S.IsDerivedFrom(InitType, ToType))
4475 return TryCopyInitialization(S, From->getInit(0), ToType,
4476 SuppressUserConversions,
4477 InOverloadResolution,
4478 AllowObjCWritebackConversion);
4479 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004480 // FIXME: Check the other conditions here: array of character type,
4481 // initializer is a string literal.
4482 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004483 InitializedEntity Entity =
4484 InitializedEntity::InitializeParameter(S.Context, ToType,
4485 /*Consumed=*/false);
4486 if (S.CanPerformCopyInitialization(Entity, From)) {
4487 Result.setStandard();
4488 Result.Standard.setAsIdentityConversion();
4489 Result.Standard.setFromType(ToType);
4490 Result.Standard.setAllToTypes(ToType);
4491 return Result;
4492 }
4493 }
4494 }
4495
4496 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004497 // C++11 [over.ics.list]p2:
4498 // If the parameter type is std::initializer_list<X> or "array of X" and
4499 // all the elements can be implicitly converted to X, the implicit
4500 // conversion sequence is the worst conversion necessary to convert an
4501 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004502 //
4503 // C++14 [over.ics.list]p3:
4504 // Otherwise, if the parameter type is “array of N X”, if the initializer
4505 // list has exactly N elements or if it has fewer than N elements and X is
4506 // default-constructible, and if all the elements of the initializer list
4507 // can be implicitly converted to X, the implicit conversion sequence is
4508 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004509 //
4510 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004511 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004512 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004513 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004514 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004515 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004516 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004517 if (!X.isNull()) {
4518 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4519 Expr *Init = From->getInit(i);
4520 ImplicitConversionSequence ICS =
4521 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4522 InOverloadResolution,
4523 AllowObjCWritebackConversion);
4524 // If a single element isn't convertible, fail.
4525 if (ICS.isBad()) {
4526 Result = ICS;
4527 break;
4528 }
4529 // Otherwise, look for the worst conversion.
4530 if (Result.isBad() ||
4531 CompareImplicitConversionSequences(S, ICS, Result) ==
4532 ImplicitConversionSequence::Worse)
4533 Result = ICS;
4534 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004535
4536 // For an empty list, we won't have computed any conversion sequence.
4537 // Introduce the identity conversion sequence.
4538 if (From->getNumInits() == 0) {
4539 Result.setStandard();
4540 Result.Standard.setAsIdentityConversion();
4541 Result.Standard.setFromType(ToType);
4542 Result.Standard.setAllToTypes(ToType);
4543 }
4544
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004545 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004546 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004547 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004548
Larisse Voufo19d08672015-01-27 18:47:05 +00004549 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004550 // C++11 [over.ics.list]p3:
4551 // Otherwise, if the parameter is a non-aggregate class X and overload
4552 // resolution chooses a single best constructor [...] the implicit
4553 // conversion sequence is a user-defined conversion sequence. If multiple
4554 // constructors are viable but none is better than the others, the
4555 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004556 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4557 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004558 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4559 /*AllowExplicit=*/false,
4560 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004561 AllowObjCWritebackConversion,
4562 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004563 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004564
Larisse Voufo19d08672015-01-27 18:47:05 +00004565 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004566 // C++11 [over.ics.list]p4:
4567 // Otherwise, if the parameter has an aggregate type which can be
4568 // initialized from the initializer list [...] the implicit conversion
4569 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004570 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004571 // Type is an aggregate, argument is an init list. At this point it comes
4572 // down to checking whether the initialization works.
4573 // FIXME: Find out whether this parameter is consumed or not.
4574 InitializedEntity Entity =
4575 InitializedEntity::InitializeParameter(S.Context, ToType,
4576 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004577 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004578 Result.setUserDefined();
4579 Result.UserDefined.Before.setAsIdentityConversion();
4580 // Initializer lists don't have a type.
4581 Result.UserDefined.Before.setFromType(QualType());
4582 Result.UserDefined.Before.setAllToTypes(QualType());
4583
4584 Result.UserDefined.After.setAsIdentityConversion();
4585 Result.UserDefined.After.setFromType(ToType);
4586 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004587 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004588 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004589 return Result;
4590 }
4591
Larisse Voufo19d08672015-01-27 18:47:05 +00004592 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004593 // C++11 [over.ics.list]p5:
4594 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004595 if (ToType->isReferenceType()) {
4596 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4597 // mention initializer lists in any way. So we go by what list-
4598 // initialization would do and try to extrapolate from that.
4599
4600 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4601
4602 // If the initializer list has a single element that is reference-related
4603 // to the parameter type, we initialize the reference from that.
4604 if (From->getNumInits() == 1) {
4605 Expr *Init = From->getInit(0);
4606
4607 QualType T2 = Init->getType();
4608
4609 // If the initializer is the address of an overloaded function, try
4610 // to resolve the overloaded function. If all goes well, T2 is the
4611 // type of the resulting function.
4612 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4613 DeclAccessPair Found;
4614 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4615 Init, ToType, false, Found))
4616 T2 = Fn->getType();
4617 }
4618
4619 // Compute some basic properties of the types and the initializer.
4620 bool dummy1 = false;
4621 bool dummy2 = false;
4622 bool dummy3 = false;
4623 Sema::ReferenceCompareResult RefRelationship
4624 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4625 dummy2, dummy3);
4626
Richard Smith4d2bbd72013-09-06 01:22:42 +00004627 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004628 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4629 SuppressUserConversions,
4630 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004631 }
Sebastian Redldf888642011-12-03 14:54:30 +00004632 }
4633
4634 // Otherwise, we bind the reference to a temporary created from the
4635 // initializer list.
4636 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4637 InOverloadResolution,
4638 AllowObjCWritebackConversion);
4639 if (Result.isFailure())
4640 return Result;
4641 assert(!Result.isEllipsis() &&
4642 "Sub-initialization cannot result in ellipsis conversion.");
4643
4644 // Can we even bind to a temporary?
4645 if (ToType->isRValueReferenceType() ||
4646 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4647 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4648 Result.UserDefined.After;
4649 SCS.ReferenceBinding = true;
4650 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4651 SCS.BindsToRvalue = true;
4652 SCS.BindsToFunctionLvalue = false;
4653 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4654 SCS.ObjCLifetimeConversionBinding = false;
4655 } else
4656 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4657 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004658 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004659 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004660
Larisse Voufo19d08672015-01-27 18:47:05 +00004661 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004662 // C++11 [over.ics.list]p6:
4663 // Otherwise, if the parameter type is not a class:
4664 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004665 // - if the initializer list has one element that is not itself an
4666 // initializer list, the implicit conversion sequence is the one
4667 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004668 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004669 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004670 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4671 SuppressUserConversions,
4672 InOverloadResolution,
4673 AllowObjCWritebackConversion);
4674 // - if the initializer list has no elements, the implicit conversion
4675 // sequence is the identity conversion.
4676 else if (NumInits == 0) {
4677 Result.setStandard();
4678 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004679 Result.Standard.setFromType(ToType);
4680 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004681 }
4682 return Result;
4683 }
4684
Larisse Voufo19d08672015-01-27 18:47:05 +00004685 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004686 // C++11 [over.ics.list]p7:
4687 // In all cases other than those enumerated above, no conversion is possible
4688 return Result;
4689}
4690
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004691/// TryCopyInitialization - Try to copy-initialize a value of type
4692/// ToType from the expression From. Return the implicit conversion
4693/// sequence required to pass this argument, which may be a bad
4694/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004695/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004696/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004697static ImplicitConversionSequence
4698TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004699 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004700 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004701 bool AllowObjCWritebackConversion,
4702 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004703 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4704 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4705 InOverloadResolution,AllowObjCWritebackConversion);
4706
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004707 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004708 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004709 /*FIXME:*/From->getLocStart(),
4710 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004711 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004712
John McCall5c32be02010-08-24 20:38:10 +00004713 return TryImplicitConversion(S, From, ToType,
4714 SuppressUserConversions,
4715 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004716 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004717 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004718 AllowObjCWritebackConversion,
4719 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004720}
4721
Anna Zaks1b068122011-07-28 19:46:48 +00004722static bool TryCopyInitialization(const CanQualType FromQTy,
4723 const CanQualType ToQTy,
4724 Sema &S,
4725 SourceLocation Loc,
4726 ExprValueKind FromVK) {
4727 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4728 ImplicitConversionSequence ICS =
4729 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4730
4731 return !ICS.isBad();
4732}
4733
Douglas Gregor436424c2008-11-18 23:14:02 +00004734/// TryObjectArgumentInitialization - Try to initialize the object
4735/// parameter of the given member function (@c Method) from the
4736/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004737static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004738TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004739 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004740 CXXMethodDecl *Method,
4741 CXXRecordDecl *ActingContext) {
4742 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004743 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4744 // const volatile object.
4745 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4746 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004747 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004748
4749 // Set up the conversion sequence as a "bad" conversion, to allow us
4750 // to exit early.
4751 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004752
4753 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004754 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004755 FromType = PT->getPointeeType();
4756
Douglas Gregor02824322011-01-26 19:30:28 +00004757 // When we had a pointer, it's implicitly dereferenced, so we
4758 // better have an lvalue.
4759 assert(FromClassification.isLValue());
4760 }
4761
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004762 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004763
Douglas Gregor02824322011-01-26 19:30:28 +00004764 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004766 // parameter is
4767 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004768 // - "lvalue reference to cv X" for functions declared without a
4769 // ref-qualifier or with the & ref-qualifier
4770 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004771 // ref-qualifier
4772 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004773 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004774 // cv-qualification on the member function declaration.
4775 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004776 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004777 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004778 // (C++ [over.match.funcs]p5). We perform a simplified version of
4779 // reference binding here, that allows class rvalues to bind to
4780 // non-constant references.
4781
Douglas Gregor02824322011-01-26 19:30:28 +00004782 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004783 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004784 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004785 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004786 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004787 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004788 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004789 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004790 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004791
4792 // Check that we have either the same type or a derived type. It
4793 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004794 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004795 ImplicitConversionKind SecondKind;
4796 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4797 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004798 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004799 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004800 else {
John McCall65eb8792010-02-25 01:37:24 +00004801 ICS.setBad(BadConversionSequence::unrelated_class,
4802 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004803 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004804 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004805
Douglas Gregor02824322011-01-26 19:30:28 +00004806 // Check the ref-qualifier.
4807 switch (Method->getRefQualifier()) {
4808 case RQ_None:
4809 // Do nothing; we don't care about lvalueness or rvalueness.
4810 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004811
Douglas Gregor02824322011-01-26 19:30:28 +00004812 case RQ_LValue:
4813 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4814 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004815 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004816 ImplicitParamType);
4817 return ICS;
4818 }
4819 break;
4820
4821 case RQ_RValue:
4822 if (!FromClassification.isRValue()) {
4823 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004824 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004825 ImplicitParamType);
4826 return ICS;
4827 }
4828 break;
4829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830
Douglas Gregor436424c2008-11-18 23:14:02 +00004831 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004832 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004833 ICS.Standard.setAsIdentityConversion();
4834 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004835 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004836 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004837 ICS.Standard.ReferenceBinding = true;
4838 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004840 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004841 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4842 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4843 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004844 return ICS;
4845}
4846
4847/// PerformObjectArgumentInitialization - Perform initialization of
4848/// the implicit object parameter for the given Method with the given
4849/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004850ExprResult
4851Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004852 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004853 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004854 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004855 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004856 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004857 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004858
Douglas Gregor02824322011-01-26 19:30:28 +00004859 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004860 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004861 FromRecordType = PT->getPointeeType();
4862 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004863 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004864 } else {
4865 FromRecordType = From->getType();
4866 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004867 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004868 }
4869
John McCall6e9f8f62009-12-03 04:06:58 +00004870 // Note that we always use the true parent context when performing
4871 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004872 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4873 *this, From->getType(), FromClassification, Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004874 if (ICS.isBad()) {
4875 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4876 Qualifiers FromQs = FromRecordType.getQualifiers();
4877 Qualifiers ToQs = DestType.getQualifiers();
4878 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4879 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004880 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004881 diag::err_member_function_call_bad_cvr)
4882 << Method->getDeclName() << FromRecordType << (CVR - 1)
4883 << From->getSourceRange();
4884 Diag(Method->getLocation(), diag::note_previous_decl)
4885 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004886 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004887 }
4888 }
4889
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004890 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004891 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004892 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004893 }
Mike Stump11289f42009-09-09 15:08:12 +00004894
John Wiegley01296292011-04-08 18:41:53 +00004895 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4896 ExprResult FromRes =
4897 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4898 if (FromRes.isInvalid())
4899 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004900 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004901 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004902
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004903 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004904 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004905 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004906 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00004907}
4908
Douglas Gregor5fb53972009-01-14 15:45:31 +00004909/// TryContextuallyConvertToBool - Attempt to contextually convert the
4910/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004911static ImplicitConversionSequence
4912TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004913 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004914 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004915 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004916 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004917 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004918 /*AllowObjCWritebackConversion=*/false,
4919 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004920}
4921
4922/// PerformContextuallyConvertToBool - Perform a contextual conversion
4923/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004924ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004925 if (checkPlaceholderForOverload(*this, From))
4926 return ExprError();
4927
John McCall5c32be02010-08-24 20:38:10 +00004928 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004929 if (!ICS.isBad())
4930 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004931
Fariborz Jahanian76197412009-11-18 18:26:29 +00004932 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004933 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004934 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004935 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004936 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004937}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004938
Richard Smithf8379a02012-01-18 23:55:52 +00004939/// Check that the specified conversion is permitted in a converted constant
4940/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4941/// is acceptable.
4942static bool CheckConvertedConstantConversions(Sema &S,
4943 StandardConversionSequence &SCS) {
4944 // Since we know that the target type is an integral or unscoped enumeration
4945 // type, most conversion kinds are impossible. All possible First and Third
4946 // conversions are fine.
4947 switch (SCS.Second) {
4948 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00004949 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00004950 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00004951 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00004952 return true;
4953
4954 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004955 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00004956 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4957 // conversion, so we allow it in a converted constant expression.
4958 //
4959 // FIXME: Per core issue 1407, we should not allow this, but that breaks
4960 // a lot of popular code. We should at least add a warning for this
4961 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00004962 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4963 SCS.getToType(2)->isBooleanType();
4964
Richard Smith410cc892014-11-26 03:26:53 +00004965 case ICK_Pointer_Conversion:
4966 case ICK_Pointer_Member:
4967 // C++1z: null pointer conversions and null member pointer conversions are
4968 // only permitted if the source type is std::nullptr_t.
4969 return SCS.getFromType()->isNullPtrType();
4970
4971 case ICK_Floating_Promotion:
4972 case ICK_Complex_Promotion:
4973 case ICK_Floating_Conversion:
4974 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004975 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00004976 case ICK_Compatible_Conversion:
4977 case ICK_Derived_To_Base:
4978 case ICK_Vector_Conversion:
4979 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00004980 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00004981 case ICK_Block_Pointer_Conversion:
4982 case ICK_TransparentUnionConversion:
4983 case ICK_Writeback_Conversion:
4984 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004985 return false;
4986
4987 case ICK_Lvalue_To_Rvalue:
4988 case ICK_Array_To_Pointer:
4989 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00004990 llvm_unreachable("found a first conversion kind in Second");
4991
Richard Smithf8379a02012-01-18 23:55:52 +00004992 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00004993 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00004994
4995 case ICK_Num_Conversion_Kinds:
4996 break;
4997 }
4998
4999 llvm_unreachable("unknown conversion kind");
5000}
5001
5002/// CheckConvertedConstantExpression - Check that the expression From is a
5003/// converted constant expression of type T, perform the conversion and produce
5004/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00005005static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5006 QualType T, APValue &Value,
5007 Sema::CCEKind CCE,
5008 bool RequireInt) {
5009 assert(S.getLangOpts().CPlusPlus11 &&
5010 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005011
Richard Smith410cc892014-11-26 03:26:53 +00005012 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005013 return ExprError();
5014
Richard Smith410cc892014-11-26 03:26:53 +00005015 // C++1z [expr.const]p3:
5016 // A converted constant expression of type T is an expression,
5017 // implicitly converted to type T, where the converted
5018 // expression is a constant expression and the implicit conversion
5019 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005020 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005021 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005022 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005023 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005024 /*AllowObjcWritebackConversion=*/false,
5025 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005026 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005027 switch (ICS.getKind()) {
5028 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005029 SCS = &ICS.Standard;
5030 break;
5031 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005032 // We are converting to a non-class type, so the Before sequence
5033 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005034 SCS = &ICS.UserDefined.After;
5035 break;
5036 case ImplicitConversionSequence::AmbiguousConversion:
5037 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005038 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5039 return S.Diag(From->getLocStart(),
5040 diag::err_typecheck_converted_constant_expression)
5041 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005042 return ExprError();
5043
5044 case ImplicitConversionSequence::EllipsisConversion:
5045 llvm_unreachable("ellipsis conversion in converted constant expression");
5046 }
5047
Richard Smith410cc892014-11-26 03:26:53 +00005048 // Check that we would only use permitted conversions.
5049 if (!CheckConvertedConstantConversions(S, *SCS)) {
5050 return S.Diag(From->getLocStart(),
5051 diag::err_typecheck_converted_constant_expression_disallowed)
5052 << From->getType() << From->getSourceRange() << T;
5053 }
5054 // [...] and where the reference binding (if any) binds directly.
5055 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5056 return S.Diag(From->getLocStart(),
5057 diag::err_typecheck_converted_constant_expression_indirect)
5058 << From->getType() << From->getSourceRange() << T;
5059 }
5060
5061 ExprResult Result =
5062 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005063 if (Result.isInvalid())
5064 return Result;
5065
5066 // Check for a narrowing implicit conversion.
5067 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005068 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005069 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005070 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005071 case NK_Variable_Narrowing:
5072 // Implicit conversion to a narrower type, and the value is not a constant
5073 // expression. We'll diagnose this in a moment.
5074 case NK_Not_Narrowing:
5075 break;
5076
5077 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005078 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005079 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005080 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005081 break;
5082
5083 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005084 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005085 << CCE << /*Constant*/0 << From->getType() << T;
5086 break;
5087 }
5088
5089 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005090 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005091 Expr::EvalResult Eval;
5092 Eval.Diag = &Notes;
5093
Richard Smith410cc892014-11-26 03:26:53 +00005094 if ((T->isReferenceType()
5095 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5096 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5097 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005098 // The expression can't be folded, so we can't keep it at this position in
5099 // the AST.
5100 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005101 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005102 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005103
5104 if (Notes.empty()) {
5105 // It's a constant expression.
5106 return Result;
5107 }
Richard Smithf8379a02012-01-18 23:55:52 +00005108 }
5109
5110 // It's not a constant expression. Produce an appropriate diagnostic.
5111 if (Notes.size() == 1 &&
5112 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005113 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005114 else {
Richard Smith410cc892014-11-26 03:26:53 +00005115 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005116 << CCE << From->getSourceRange();
5117 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005118 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005119 }
Richard Smith410cc892014-11-26 03:26:53 +00005120 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005121}
5122
Richard Smith410cc892014-11-26 03:26:53 +00005123ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5124 APValue &Value, CCEKind CCE) {
5125 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5126}
5127
5128ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5129 llvm::APSInt &Value,
5130 CCEKind CCE) {
5131 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5132
5133 APValue V;
5134 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5135 if (!R.isInvalid())
5136 Value = V.getInt();
5137 return R;
5138}
5139
5140
John McCallfec112d2011-09-09 06:11:02 +00005141/// dropPointerConversions - If the given standard conversion sequence
5142/// involves any pointer conversions, remove them. This may change
5143/// the result type of the conversion sequence.
5144static void dropPointerConversion(StandardConversionSequence &SCS) {
5145 if (SCS.Second == ICK_Pointer_Conversion) {
5146 SCS.Second = ICK_Identity;
5147 SCS.Third = ICK_Identity;
5148 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5149 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005150}
John McCall5c32be02010-08-24 20:38:10 +00005151
John McCallfec112d2011-09-09 06:11:02 +00005152/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5153/// convert the expression From to an Objective-C pointer type.
5154static ImplicitConversionSequence
5155TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5156 // Do an implicit conversion to 'id'.
5157 QualType Ty = S.Context.getObjCIdType();
5158 ImplicitConversionSequence ICS
5159 = TryImplicitConversion(S, From, Ty,
5160 // FIXME: Are these flags correct?
5161 /*SuppressUserConversions=*/false,
5162 /*AllowExplicit=*/true,
5163 /*InOverloadResolution=*/false,
5164 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005165 /*AllowObjCWritebackConversion=*/false,
5166 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005167
5168 // Strip off any final conversions to 'id'.
5169 switch (ICS.getKind()) {
5170 case ImplicitConversionSequence::BadConversion:
5171 case ImplicitConversionSequence::AmbiguousConversion:
5172 case ImplicitConversionSequence::EllipsisConversion:
5173 break;
5174
5175 case ImplicitConversionSequence::UserDefinedConversion:
5176 dropPointerConversion(ICS.UserDefined.After);
5177 break;
5178
5179 case ImplicitConversionSequence::StandardConversion:
5180 dropPointerConversion(ICS.Standard);
5181 break;
5182 }
5183
5184 return ICS;
5185}
5186
5187/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5188/// conversion of the expression From to an Objective-C pointer type.
5189ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005190 if (checkPlaceholderForOverload(*this, From))
5191 return ExprError();
5192
John McCall8b07ec22010-05-15 11:32:37 +00005193 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005194 ImplicitConversionSequence ICS =
5195 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005196 if (!ICS.isBad())
5197 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005198 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005199}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005200
Richard Smith8dd34252012-02-04 07:07:42 +00005201/// Determine whether the provided type is an integral type, or an enumeration
5202/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005203bool Sema::ICEConvertDiagnoser::match(QualType T) {
5204 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5205 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005206}
5207
Larisse Voufo236bec22013-06-10 06:50:24 +00005208static ExprResult
5209diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5210 Sema::ContextualImplicitConverter &Converter,
5211 QualType T, UnresolvedSetImpl &ViableConversions) {
5212
5213 if (Converter.Suppress)
5214 return ExprError();
5215
5216 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5217 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5218 CXXConversionDecl *Conv =
5219 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5220 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5221 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5222 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005223 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005224}
5225
5226static bool
5227diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5228 Sema::ContextualImplicitConverter &Converter,
5229 QualType T, bool HadMultipleCandidates,
5230 UnresolvedSetImpl &ExplicitConversions) {
5231 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5232 DeclAccessPair Found = ExplicitConversions[0];
5233 CXXConversionDecl *Conversion =
5234 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5235
5236 // The user probably meant to invoke the given explicit
5237 // conversion; use it.
5238 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5239 std::string TypeStr;
5240 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5241
5242 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5243 << FixItHint::CreateInsertion(From->getLocStart(),
5244 "static_cast<" + TypeStr + ">(")
5245 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005246 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005247 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5248
5249 // If we aren't in a SFINAE context, build a call to the
5250 // explicit conversion function.
5251 if (SemaRef.isSFINAEContext())
5252 return true;
5253
Craig Topperc3ec1492014-05-26 06:22:03 +00005254 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005255 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5256 HadMultipleCandidates);
5257 if (Result.isInvalid())
5258 return true;
5259 // Record usage of conversion in an implicit cast.
5260 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005261 CK_UserDefinedConversion, Result.get(),
5262 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005263 }
5264 return false;
5265}
5266
5267static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5268 Sema::ContextualImplicitConverter &Converter,
5269 QualType T, bool HadMultipleCandidates,
5270 DeclAccessPair &Found) {
5271 CXXConversionDecl *Conversion =
5272 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005273 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005274
5275 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5276 if (!Converter.SuppressConversion) {
5277 if (SemaRef.isSFINAEContext())
5278 return true;
5279
5280 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5281 << From->getSourceRange();
5282 }
5283
5284 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5285 HadMultipleCandidates);
5286 if (Result.isInvalid())
5287 return true;
5288 // Record usage of conversion in an implicit cast.
5289 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005290 CK_UserDefinedConversion, Result.get(),
5291 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005292 return false;
5293}
5294
5295static ExprResult finishContextualImplicitConversion(
5296 Sema &SemaRef, SourceLocation Loc, Expr *From,
5297 Sema::ContextualImplicitConverter &Converter) {
5298 if (!Converter.match(From->getType()) && !Converter.Suppress)
5299 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5300 << From->getSourceRange();
5301
5302 return SemaRef.DefaultLvalueConversion(From);
5303}
5304
5305static void
5306collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5307 UnresolvedSetImpl &ViableConversions,
5308 OverloadCandidateSet &CandidateSet) {
5309 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5310 DeclAccessPair FoundDecl = ViableConversions[I];
5311 NamedDecl *D = FoundDecl.getDecl();
5312 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5313 if (isa<UsingShadowDecl>(D))
5314 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5315
5316 CXXConversionDecl *Conv;
5317 FunctionTemplateDecl *ConvTemplate;
5318 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5319 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5320 else
5321 Conv = cast<CXXConversionDecl>(D);
5322
5323 if (ConvTemplate)
5324 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005325 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5326 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005327 else
5328 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005329 ToType, CandidateSet,
5330 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005331 }
5332}
5333
Richard Smithccc11812013-05-21 19:05:48 +00005334/// \brief Attempt to convert the given expression to a type which is accepted
5335/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005336///
Richard Smithccc11812013-05-21 19:05:48 +00005337/// This routine will attempt to convert an expression of class type to a
5338/// type accepted by the specified converter. In C++11 and before, the class
5339/// must have a single non-explicit conversion function converting to a matching
5340/// type. In C++1y, there can be multiple such conversion functions, but only
5341/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005342///
Douglas Gregor4799d032010-06-30 00:20:43 +00005343/// \param Loc The source location of the construct that requires the
5344/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005345///
James Dennett18348b62012-06-22 08:52:37 +00005346/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005347///
Richard Smithccc11812013-05-21 19:05:48 +00005348/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005349///
Douglas Gregor4799d032010-06-30 00:20:43 +00005350/// \returns The expression, converted to an integral or enumeration type if
5351/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005352ExprResult Sema::PerformContextualImplicitConversion(
5353 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005354 // We can't perform any more checking for type-dependent expressions.
5355 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005356 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005357
Eli Friedman1da70392012-01-26 00:26:18 +00005358 // Process placeholders immediately.
5359 if (From->hasPlaceholderType()) {
5360 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005361 if (result.isInvalid())
5362 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005363 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005364 }
5365
Richard Smithccc11812013-05-21 19:05:48 +00005366 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005367 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005368 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005369 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005370
5371 // FIXME: Check for missing '()' if T is a function type?
5372
Richard Smithccc11812013-05-21 19:05:48 +00005373 // We can only perform contextual implicit conversions on objects of class
5374 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005375 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005376 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005377 if (!Converter.Suppress)
5378 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005379 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005381
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005382 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005383 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005384 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005385 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005386
5387 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5388 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5389
Craig Toppere14c0f82014-03-12 04:55:44 +00005390 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005391 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005392 }
Richard Smithccc11812013-05-21 19:05:48 +00005393 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005394
5395 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005396 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005397
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005398 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005399 UnresolvedSet<4>
5400 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005401 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005402 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo236bec22013-06-10 06:50:24 +00005403 CXXRecordDecl::conversion_iterator> Conversions =
5404 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005405
Larisse Voufo236bec22013-06-10 06:50:24 +00005406 bool HadMultipleCandidates =
5407 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005408
Larisse Voufo236bec22013-06-10 06:50:24 +00005409 // To check that there is only one target type, in C++1y:
5410 QualType ToType;
5411 bool HasUniqueTargetType = true;
5412
5413 // Collect explicit or viable (potentially in C++1y) conversions.
5414 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5415 E = Conversions.second;
5416 I != E; ++I) {
5417 NamedDecl *D = (*I)->getUnderlyingDecl();
5418 CXXConversionDecl *Conversion;
5419 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5420 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005421 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005422 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5423 else
5424 continue; // C++11 does not consider conversion operator templates(?).
5425 } else
5426 Conversion = cast<CXXConversionDecl>(D);
5427
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005428 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005429 "Conversion operator templates are considered potentially "
5430 "viable in C++1y");
5431
5432 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5433 if (Converter.match(CurToType) || ConvTemplate) {
5434
5435 if (Conversion->isExplicit()) {
5436 // FIXME: For C++1y, do we need this restriction?
5437 // cf. diagnoseNoViableConversion()
5438 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005439 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005440 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005441 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005442 if (ToType.isNull())
5443 ToType = CurToType.getUnqualifiedType();
5444 else if (HasUniqueTargetType &&
5445 (CurToType.getUnqualifiedType() != ToType))
5446 HasUniqueTargetType = false;
5447 }
5448 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005449 }
Richard Smith8dd34252012-02-04 07:07:42 +00005450 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005451 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005452
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005453 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005454 // C++1y [conv]p6:
5455 // ... An expression e of class type E appearing in such a context
5456 // is said to be contextually implicitly converted to a specified
5457 // type T and is well-formed if and only if e can be implicitly
5458 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005459 // for conversion functions whose return type is cv T or reference to
5460 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005461 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005462
Larisse Voufo236bec22013-06-10 06:50:24 +00005463 // If no unique T is found:
5464 if (ToType.isNull()) {
5465 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5466 HadMultipleCandidates,
5467 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005468 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005469 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005470 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005471
Larisse Voufo236bec22013-06-10 06:50:24 +00005472 // If more than one unique Ts are found:
5473 if (!HasUniqueTargetType)
5474 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5475 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005476
Larisse Voufo236bec22013-06-10 06:50:24 +00005477 // If one unique T is found:
5478 // First, build a candidate set from the previously recorded
5479 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005480 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005481 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5482 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005483
Larisse Voufo236bec22013-06-10 06:50:24 +00005484 // Then, perform overload resolution over the candidate set.
5485 OverloadCandidateSet::iterator Best;
5486 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5487 case OR_Success: {
5488 // Apply this conversion.
5489 DeclAccessPair Found =
5490 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5491 if (recordConversion(*this, Loc, From, Converter, T,
5492 HadMultipleCandidates, Found))
5493 return ExprError();
5494 break;
5495 }
5496 case OR_Ambiguous:
5497 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5498 ViableConversions);
5499 case OR_No_Viable_Function:
5500 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5501 HadMultipleCandidates,
5502 ExplicitConversions))
5503 return ExprError();
5504 // fall through 'OR_Deleted' case.
5505 case OR_Deleted:
5506 // We'll complain below about a non-integral condition type.
5507 break;
5508 }
5509 } else {
5510 switch (ViableConversions.size()) {
5511 case 0: {
5512 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5513 HadMultipleCandidates,
5514 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005515 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005516
Larisse Voufo236bec22013-06-10 06:50:24 +00005517 // We'll complain below about a non-integral condition type.
5518 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005519 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005520 case 1: {
5521 // Apply this conversion.
5522 DeclAccessPair Found = ViableConversions[0];
5523 if (recordConversion(*this, Loc, From, Converter, T,
5524 HadMultipleCandidates, Found))
5525 return ExprError();
5526 break;
5527 }
5528 default:
5529 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5530 ViableConversions);
5531 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005533
Larisse Voufo236bec22013-06-10 06:50:24 +00005534 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005535}
5536
Richard Smith100b24a2014-04-17 01:52:14 +00005537/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5538/// an acceptable non-member overloaded operator for a call whose
5539/// arguments have types T1 (and, if non-empty, T2). This routine
5540/// implements the check in C++ [over.match.oper]p3b2 concerning
5541/// enumeration types.
5542static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5543 FunctionDecl *Fn,
5544 ArrayRef<Expr *> Args) {
5545 QualType T1 = Args[0]->getType();
5546 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5547
5548 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5549 return true;
5550
5551 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5552 return true;
5553
5554 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5555 if (Proto->getNumParams() < 1)
5556 return false;
5557
5558 if (T1->isEnumeralType()) {
5559 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5560 if (Context.hasSameUnqualifiedType(T1, ArgType))
5561 return true;
5562 }
5563
5564 if (Proto->getNumParams() < 2)
5565 return false;
5566
5567 if (!T2.isNull() && T2->isEnumeralType()) {
5568 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5569 if (Context.hasSameUnqualifiedType(T2, ArgType))
5570 return true;
5571 }
5572
5573 return false;
5574}
5575
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005576/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005577/// candidate functions, using the given function call arguments. If
5578/// @p SuppressUserConversions, then don't allow user-defined
5579/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005580///
James Dennett2a4d13c2012-06-15 07:13:21 +00005581/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005582/// based on an incomplete set of function arguments. This feature is used by
5583/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005584void
5585Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005586 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005587 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005588 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005589 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005590 bool PartialOverloading,
5591 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005592 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005593 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005594 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005595 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005596 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005597
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005598 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005599 if (!isa<CXXConstructorDecl>(Method)) {
5600 // If we get here, it's because we're calling a member function
5601 // that is named without a member access expression (e.g.,
5602 // "this->f") that was either written explicitly or created
5603 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005604 // function, e.g., X::f(). We use an empty type for the implied
5605 // object argument (C++ [over.call.func]p3), and the acting context
5606 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005607 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005609 Args, CandidateSet, SuppressUserConversions,
5610 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005611 return;
5612 }
5613 // We treat a constructor like a non-member function, since its object
5614 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005615 }
5616
Douglas Gregorff7028a2009-11-13 23:59:09 +00005617 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005618 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005619
Richard Smith100b24a2014-04-17 01:52:14 +00005620 // C++ [over.match.oper]p3:
5621 // if no operand has a class type, only those non-member functions in the
5622 // lookup set that have a first parameter of type T1 or "reference to
5623 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5624 // is a right operand) a second parameter of type T2 or "reference to
5625 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5626 // candidate functions.
5627 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5628 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5629 return;
5630
Richard Smith8b86f2d2013-11-04 01:48:18 +00005631 // C++11 [class.copy]p11: [DR1402]
5632 // A defaulted move constructor that is defined as deleted is ignored by
5633 // overload resolution.
5634 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5635 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5636 Constructor->isMoveConstructor())
5637 return;
5638
Douglas Gregor27381f32009-11-23 12:27:39 +00005639 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005640 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005641
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005642 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005643 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005644 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005645 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005646 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005647 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005648 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005649 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005650
John McCall578a1f82014-12-14 01:46:53 +00005651 if (Constructor) {
5652 // C++ [class.copy]p3:
5653 // A member function template is never instantiated to perform the copy
5654 // of a class object to an object of its class type.
5655 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5656 if (Args.size() == 1 &&
5657 Constructor->isSpecializationCopyingObject() &&
5658 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5659 IsDerivedFrom(Args[0]->getType(), ClassType))) {
5660 Candidate.Viable = false;
5661 Candidate.FailureKind = ovl_fail_illegal_constructor;
5662 return;
5663 }
5664 }
5665
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005666 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005667
5668 // (C++ 13.3.2p2): A candidate function having fewer than m
5669 // parameters is viable only if it has an ellipsis in its parameter
5670 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005671 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005672 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005673 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005674 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005675 return;
5676 }
5677
5678 // (C++ 13.3.2p2): A candidate function having more than m parameters
5679 // is viable only if the (m+1)st parameter has a default argument
5680 // (8.3.6). For the purposes of overload resolution, the
5681 // parameter list is truncated on the right, so that there are
5682 // exactly m parameters.
5683 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005684 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005685 // Not enough arguments.
5686 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005687 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005688 return;
5689 }
5690
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005691 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005692 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005693 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005694 // Skip the check for callers that are implicit members, because in this
5695 // case we may not yet know what the member's target is; the target is
5696 // inferred for the member automatically, based on the bases and fields of
5697 // the class.
5698 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005699 Candidate.Viable = false;
5700 Candidate.FailureKind = ovl_fail_bad_target;
5701 return;
5702 }
5703
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005704 // Determine the implicit conversion sequences for each of the
5705 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005706 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005707 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005708 // (C++ 13.3.2p3): for F to be a viable function, there shall
5709 // exist for each argument an implicit conversion sequence
5710 // (13.3.3.1) that converts that argument to the corresponding
5711 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005712 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005713 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005714 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005715 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005716 /*InOverloadResolution=*/true,
5717 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005718 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005719 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005720 if (Candidate.Conversions[ArgIdx].isBad()) {
5721 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005722 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005723 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005724 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005725 } else {
5726 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5727 // argument for which there is no corresponding parameter is
5728 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005729 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005730 }
5731 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005732
5733 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5734 Candidate.Viable = false;
5735 Candidate.FailureKind = ovl_fail_enable_if;
5736 Candidate.DeductionFailure.Data = FailedAttr;
5737 return;
5738 }
5739}
5740
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005741ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005742 bool IsInstance) {
5743 SmallVector<ObjCMethodDecl*, 4> Methods;
5744 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5745 return nullptr;
5746
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005747 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5748 bool Match = true;
5749 ObjCMethodDecl *Method = Methods[b];
5750 unsigned NumNamedArgs = Sel.getNumArgs();
5751 // Method might have more arguments than selector indicates. This is due
5752 // to addition of c-style arguments in method.
5753 if (Method->param_size() > NumNamedArgs)
5754 NumNamedArgs = Method->param_size();
5755 if (Args.size() < NumNamedArgs)
5756 continue;
5757
5758 for (unsigned i = 0; i < NumNamedArgs; i++) {
5759 // We can't do any type-checking on a type-dependent argument.
5760 if (Args[i]->isTypeDependent()) {
5761 Match = false;
5762 break;
5763 }
5764
5765 ParmVarDecl *param = Method->parameters()[i];
5766 Expr *argExpr = Args[i];
5767 assert(argExpr && "SelectBestMethod(): missing expression");
5768
5769 // Strip the unbridged-cast placeholder expression off unless it's
5770 // a consumed argument.
5771 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5772 !param->hasAttr<CFConsumedAttr>())
5773 argExpr = stripARCUnbridgedCast(argExpr);
5774
5775 // If the parameter is __unknown_anytype, move on to the next method.
5776 if (param->getType() == Context.UnknownAnyTy) {
5777 Match = false;
5778 break;
5779 }
5780
5781 ImplicitConversionSequence ConversionState
5782 = TryCopyInitialization(*this, argExpr, param->getType(),
5783 /*SuppressUserConversions*/false,
5784 /*InOverloadResolution=*/true,
5785 /*AllowObjCWritebackConversion=*/
5786 getLangOpts().ObjCAutoRefCount,
5787 /*AllowExplicit*/false);
5788 if (ConversionState.isBad()) {
5789 Match = false;
5790 break;
5791 }
5792 }
5793 // Promote additional arguments to variadic methods.
5794 if (Match && Method->isVariadic()) {
5795 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5796 if (Args[i]->isTypeDependent()) {
5797 Match = false;
5798 break;
5799 }
5800 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5801 nullptr);
5802 if (Arg.isInvalid()) {
5803 Match = false;
5804 break;
5805 }
5806 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005807 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005808 // Check for extra arguments to non-variadic methods.
5809 if (Args.size() != NumNamedArgs)
5810 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005811 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5812 // Special case when selectors have no argument. In this case, select
5813 // one with the most general result type of 'id'.
5814 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5815 QualType ReturnT = Methods[b]->getReturnType();
5816 if (ReturnT->isObjCIdType())
5817 return Methods[b];
5818 }
5819 }
5820 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005821
5822 if (Match)
5823 return Method;
5824 }
5825 return nullptr;
5826}
5827
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005828static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5829
5830EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5831 bool MissingImplicitThis) {
5832 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5833 // we need to find the first failing one.
5834 if (!Function->hasAttrs())
Craig Topperc3ec1492014-05-26 06:22:03 +00005835 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005836 AttrVec Attrs = Function->getAttrs();
5837 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5838 IsNotEnableIfAttr);
5839 if (Attrs.begin() == E)
Craig Topperc3ec1492014-05-26 06:22:03 +00005840 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005841 std::reverse(Attrs.begin(), E);
5842
5843 SFINAETrap Trap(*this);
5844
5845 // Convert the arguments.
5846 SmallVector<Expr *, 16> ConvertedArgs;
5847 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005848 bool ContainsValueDependentExpr = false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005849 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5850 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005851 !cast<CXXMethodDecl>(Function)->isStatic() &&
5852 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005853 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5854 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005855 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005856 Method, Method);
5857 if (R.isInvalid()) {
5858 InitializationFailed = true;
5859 break;
5860 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005861 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005862 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005863 } else {
5864 ExprResult R =
5865 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5866 Context,
5867 Function->getParamDecl(i)),
5868 SourceLocation(),
5869 Args[i]);
5870 if (R.isInvalid()) {
5871 InitializationFailed = true;
5872 break;
5873 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005874 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005875 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005876 }
5877 }
5878
5879 if (InitializationFailed || Trap.hasErrorOccurred())
5880 return cast<EnableIfAttr>(Attrs[0]);
5881
5882 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5883 APValue Result;
5884 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005885 if (EIA->getCond()->isValueDependent()) {
5886 // Don't even try now, we'll examine it after instantiation.
5887 continue;
5888 }
5889
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005890 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005891 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5892 if (!ContainsValueDependentExpr)
5893 return EIA;
5894 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005895 return EIA;
5896 }
5897 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005898 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005899}
5900
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005901/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005902/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005903void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005904 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005905 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005906 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005907 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005908 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00005909 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005910 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5911 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005912 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005913 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005914 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005915 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005916 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005917 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005918 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005919 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005920 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005921 } else {
John McCalla0296f72010-03-19 07:35:19 +00005922 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005923 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5924 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005925 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005926 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005927 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005928 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005929 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005930 CandidateSet, SuppressUserConversions,
5931 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005932 else
John McCalla0296f72010-03-19 07:35:19 +00005933 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005934 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005935 CandidateSet, SuppressUserConversions,
5936 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005937 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005938 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005939}
5940
John McCallf0f1cf02009-11-17 07:50:12 +00005941/// AddMethodCandidate - Adds a named decl (which is some kind of
5942/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005943void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005944 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005945 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005946 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005947 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005948 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005949 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005950 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005951
5952 if (isa<UsingShadowDecl>(Decl))
5953 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005954
John McCallf0f1cf02009-11-17 07:50:12 +00005955 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5956 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5957 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005958 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00005959 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005960 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005961 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005962 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005963 } else {
John McCalla0296f72010-03-19 07:35:19 +00005964 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005965 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005966 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005967 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005968 }
5969}
5970
Douglas Gregor436424c2008-11-18 23:14:02 +00005971/// AddMethodCandidate - Adds the given C++ member function to the set
5972/// of candidate functions, using the given function call arguments
5973/// and the object argument (@c Object). For example, in a call
5974/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5975/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5976/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005977/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005978void
John McCalla0296f72010-03-19 07:35:19 +00005979Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005980 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005981 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005982 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005983 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005984 bool SuppressUserConversions,
5985 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005986 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005987 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005988 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005989 assert(!isa<CXXConstructorDecl>(Method) &&
5990 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005991
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005992 if (!CandidateSet.isNewCandidate(Method))
5993 return;
5994
Richard Smith8b86f2d2013-11-04 01:48:18 +00005995 // C++11 [class.copy]p23: [DR1402]
5996 // A defaulted move assignment operator that is defined as deleted is
5997 // ignored by overload resolution.
5998 if (Method->isDefaulted() && Method->isDeleted() &&
5999 Method->isMoveAssignmentOperator())
6000 return;
6001
Douglas Gregor27381f32009-11-23 12:27:39 +00006002 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006003 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006004
Douglas Gregor436424c2008-11-18 23:14:02 +00006005 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006006 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006007 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006008 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006009 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006010 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006011 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006012
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006013 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006014
6015 // (C++ 13.3.2p2): A candidate function having fewer than m
6016 // parameters is viable only if it has an ellipsis in its parameter
6017 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006018 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6019 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006020 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006021 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006022 return;
6023 }
6024
6025 // (C++ 13.3.2p2): A candidate function having more than m parameters
6026 // is viable only if the (m+1)st parameter has a default argument
6027 // (8.3.6). For the purposes of overload resolution, the
6028 // parameter list is truncated on the right, so that there are
6029 // exactly m parameters.
6030 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006031 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006032 // Not enough arguments.
6033 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006034 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006035 return;
6036 }
6037
6038 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006039
John McCall6e9f8f62009-12-03 04:06:58 +00006040 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006041 // The implicit object argument is ignored.
6042 Candidate.IgnoreObjectArgument = true;
6043 else {
6044 // Determine the implicit conversion sequence for the object
6045 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00006046 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00006047 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6048 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006049 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006050 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006051 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006052 return;
6053 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006054 }
6055
Eli Bendersky291a57e2014-09-25 23:59:08 +00006056 // (CUDA B.1): Check for invalid calls between targets.
6057 if (getLangOpts().CUDA)
6058 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6059 if (CheckCUDATarget(Caller, Method)) {
6060 Candidate.Viable = false;
6061 Candidate.FailureKind = ovl_fail_bad_target;
6062 return;
6063 }
6064
Douglas Gregor436424c2008-11-18 23:14:02 +00006065 // Determine the implicit conversion sequences for each of the
6066 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006067 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006068 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006069 // (C++ 13.3.2p3): for F to be a viable function, there shall
6070 // exist for each argument an implicit conversion sequence
6071 // (13.3.3.1) that converts that argument to the corresponding
6072 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006073 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006074 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006075 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006076 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006077 /*InOverloadResolution=*/true,
6078 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006079 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006080 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006081 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006082 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006083 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006084 }
6085 } else {
6086 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6087 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006088 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006089 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006090 }
6091 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006092
6093 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6094 Candidate.Viable = false;
6095 Candidate.FailureKind = ovl_fail_enable_if;
6096 Candidate.DeductionFailure.Data = FailedAttr;
6097 return;
6098 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006099}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006100
Douglas Gregor97628d62009-08-21 00:16:32 +00006101/// \brief Add a C++ member function template as a candidate to the candidate
6102/// set, using template argument deduction to produce an appropriate member
6103/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006104void
Douglas Gregor97628d62009-08-21 00:16:32 +00006105Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006106 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006107 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006108 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006109 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006110 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006111 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006112 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006113 bool SuppressUserConversions,
6114 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006115 if (!CandidateSet.isNewCandidate(MethodTmpl))
6116 return;
6117
Douglas Gregor97628d62009-08-21 00:16:32 +00006118 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006119 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006120 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006121 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006122 // candidate functions in the usual way.113) A given name can refer to one
6123 // or more function templates and also to a set of overloaded non-template
6124 // functions. In such a case, the candidate functions generated from each
6125 // function template are combined with the set of non-template candidate
6126 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006127 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006128 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006129 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006130 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006131 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006132 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006133 Candidate.FoundDecl = FoundDecl;
6134 Candidate.Function = MethodTmpl->getTemplatedDecl();
6135 Candidate.Viable = false;
6136 Candidate.FailureKind = ovl_fail_bad_deduction;
6137 Candidate.IsSurrogate = false;
6138 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006139 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006140 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006141 Info);
6142 return;
6143 }
Mike Stump11289f42009-09-09 15:08:12 +00006144
Douglas Gregor97628d62009-08-21 00:16:32 +00006145 // Add the function template specialization produced by template argument
6146 // deduction as a candidate.
6147 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006148 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006149 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006150 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006151 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006152 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006153}
6154
Douglas Gregor05155d82009-08-21 23:19:43 +00006155/// \brief Add a C++ function template specialization as a candidate
6156/// in the candidate set, using template argument deduction to produce
6157/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006158void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006159Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006160 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006161 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006162 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006163 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006164 bool SuppressUserConversions,
6165 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006166 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6167 return;
6168
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006169 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006170 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006171 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006172 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006173 // candidate functions in the usual way.113) A given name can refer to one
6174 // or more function templates and also to a set of overloaded non-template
6175 // functions. In such a case, the candidate functions generated from each
6176 // function template are combined with the set of non-template candidate
6177 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006178 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006179 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006180 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006181 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006182 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006183 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006184 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006185 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6186 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006187 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006188 Candidate.IsSurrogate = false;
6189 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006190 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006191 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006192 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006193 return;
6194 }
Mike Stump11289f42009-09-09 15:08:12 +00006195
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006196 // Add the function template specialization produced by template argument
6197 // deduction as a candidate.
6198 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006199 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006200 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006201}
Mike Stump11289f42009-09-09 15:08:12 +00006202
Douglas Gregor4b60a152013-11-07 22:34:54 +00006203/// Determine whether this is an allowable conversion from the result
6204/// of an explicit conversion operator to the expected type, per C++
6205/// [over.match.conv]p1 and [over.match.ref]p1.
6206///
6207/// \param ConvType The return type of the conversion function.
6208///
6209/// \param ToType The type we are converting to.
6210///
6211/// \param AllowObjCPointerConversion Allow a conversion from one
6212/// Objective-C pointer to another.
6213///
6214/// \returns true if the conversion is allowable, false otherwise.
6215static bool isAllowableExplicitConversion(Sema &S,
6216 QualType ConvType, QualType ToType,
6217 bool AllowObjCPointerConversion) {
6218 QualType ToNonRefType = ToType.getNonReferenceType();
6219
6220 // Easy case: the types are the same.
6221 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6222 return true;
6223
6224 // Allow qualification conversions.
6225 bool ObjCLifetimeConversion;
6226 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6227 ObjCLifetimeConversion))
6228 return true;
6229
6230 // If we're not allowed to consider Objective-C pointer conversions,
6231 // we're done.
6232 if (!AllowObjCPointerConversion)
6233 return false;
6234
6235 // Is this an Objective-C pointer conversion?
6236 bool IncompatibleObjC = false;
6237 QualType ConvertedType;
6238 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6239 IncompatibleObjC);
6240}
6241
Douglas Gregora1f013e2008-11-07 22:36:19 +00006242/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006243/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006244/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006245/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006246/// (which may or may not be the same type as the type that the
6247/// conversion function produces).
6248void
6249Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006250 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006251 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006252 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006253 OverloadCandidateSet& CandidateSet,
6254 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006255 assert(!Conversion->getDescribedFunctionTemplate() &&
6256 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006257 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006258 if (!CandidateSet.isNewCandidate(Conversion))
6259 return;
6260
Richard Smith2a7d4812013-05-04 07:00:32 +00006261 // If the conversion function has an undeduced return type, trigger its
6262 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006263 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006264 if (DeduceReturnType(Conversion, From->getExprLoc()))
6265 return;
6266 ConvType = Conversion->getConversionType().getNonReferenceType();
6267 }
6268
Richard Smith089c3162013-09-21 21:55:46 +00006269 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6270 // operator is only a candidate if its return type is the target type or
6271 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006272 if (Conversion->isExplicit() &&
6273 !isAllowableExplicitConversion(*this, ConvType, ToType,
6274 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006275 return;
6276
Douglas Gregor27381f32009-11-23 12:27:39 +00006277 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006278 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006279
Douglas Gregora1f013e2008-11-07 22:36:19 +00006280 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006281 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006282 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006283 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006284 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006285 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006286 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006287 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006288 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006289 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006290 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006291
Douglas Gregor6affc782010-08-19 15:37:02 +00006292 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006293 // For conversion functions, the function is considered to be a member of
6294 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006295 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006296 //
6297 // Determine the implicit conversion sequence for the implicit
6298 // object parameter.
6299 QualType ImplicitParamType = From->getType();
6300 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6301 ImplicitParamType = FromPtrType->getPointeeType();
6302 CXXRecordDecl *ConversionContext
6303 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006304
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006305 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006306 = TryObjectArgumentInitialization(*this, From->getType(),
6307 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006308 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006309
John McCall0d1da222010-01-12 00:44:57 +00006310 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006311 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006312 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006313 return;
6314 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006315
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006316 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006317 // derived to base as such conversions are given Conversion Rank. They only
6318 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6319 QualType FromCanon
6320 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6321 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6322 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6323 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006324 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006325 return;
6326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006327
Douglas Gregora1f013e2008-11-07 22:36:19 +00006328 // To determine what the conversion from the result of calling the
6329 // conversion function to the type we're eventually trying to
6330 // convert to (ToType), we need to synthesize a call to the
6331 // conversion function and attempt copy initialization from it. This
6332 // makes sure that we get the right semantics with respect to
6333 // lvalues/rvalues and the type. Fortunately, we can allocate this
6334 // call on the stack and we don't need its arguments to be
6335 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006336 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006337 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006338 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6339 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006340 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006341 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006342
Richard Smith48d24642011-07-13 22:53:21 +00006343 QualType ConversionType = Conversion->getConversionType();
6344 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006345 Candidate.Viable = false;
6346 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6347 return;
6348 }
6349
Richard Smith48d24642011-07-13 22:53:21 +00006350 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006351
Mike Stump11289f42009-09-09 15:08:12 +00006352 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006353 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6354 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006355 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006356 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006357 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006358 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006359 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006360 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006361 /*InOverloadResolution=*/false,
6362 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006363
John McCall0d1da222010-01-12 00:44:57 +00006364 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006365 case ImplicitConversionSequence::StandardConversion:
6366 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006367
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006368 // C++ [over.ics.user]p3:
6369 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006370 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006371 // shall have exact match rank.
6372 if (Conversion->getPrimaryTemplate() &&
6373 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6374 Candidate.Viable = false;
6375 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006376 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006377 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006378
Douglas Gregorcba72b12011-01-21 05:18:22 +00006379 // C++0x [dcl.init.ref]p5:
6380 // In the second case, if the reference is an rvalue reference and
6381 // the second standard conversion sequence of the user-defined
6382 // conversion sequence includes an lvalue-to-rvalue conversion, the
6383 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006384 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006385 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6386 Candidate.Viable = false;
6387 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006388 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006389 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006390 break;
6391
6392 case ImplicitConversionSequence::BadConversion:
6393 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006394 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006395 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006396
6397 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006398 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006399 "Can only end up with a standard conversion sequence or failure");
6400 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006401
Craig Topper5fc8fc22014-08-27 06:28:36 +00006402 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006403 Candidate.Viable = false;
6404 Candidate.FailureKind = ovl_fail_enable_if;
6405 Candidate.DeductionFailure.Data = FailedAttr;
6406 return;
6407 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006408}
6409
Douglas Gregor05155d82009-08-21 23:19:43 +00006410/// \brief Adds a conversion function template specialization
6411/// candidate to the overload set, using template argument deduction
6412/// to deduce the template arguments of the conversion function
6413/// template from the type that we are converting to (C++
6414/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006415void
Douglas Gregor05155d82009-08-21 23:19:43 +00006416Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006417 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006418 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006419 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006420 OverloadCandidateSet &CandidateSet,
6421 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006422 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6423 "Only conversion function templates permitted here");
6424
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006425 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6426 return;
6427
Craig Toppere6706e42012-09-19 02:26:47 +00006428 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006429 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006430 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006431 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006432 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006433 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006434 Candidate.FoundDecl = FoundDecl;
6435 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6436 Candidate.Viable = false;
6437 Candidate.FailureKind = ovl_fail_bad_deduction;
6438 Candidate.IsSurrogate = false;
6439 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006440 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006441 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006442 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006443 return;
6444 }
Mike Stump11289f42009-09-09 15:08:12 +00006445
Douglas Gregor05155d82009-08-21 23:19:43 +00006446 // Add the conversion function template specialization produced by
6447 // template argument deduction as a candidate.
6448 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006449 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006450 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006451}
6452
Douglas Gregorab7897a2008-11-19 22:57:39 +00006453/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6454/// converts the given @c Object to a function pointer via the
6455/// conversion function @c Conversion, and then attempts to call it
6456/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6457/// the type of function that we'll eventually be calling.
6458void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006459 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006460 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006461 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006462 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006463 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006464 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006465 if (!CandidateSet.isNewCandidate(Conversion))
6466 return;
6467
Douglas Gregor27381f32009-11-23 12:27:39 +00006468 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006469 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006470
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006471 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006472 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006473 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006474 Candidate.Surrogate = Conversion;
6475 Candidate.Viable = true;
6476 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006477 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006478 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006479
6480 // Determine the implicit conversion sequence for the implicit
6481 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006482 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006483 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006484 Object->Classify(Context),
6485 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006486 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006487 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006488 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006489 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006490 return;
6491 }
6492
6493 // The first conversion is actually a user-defined conversion whose
6494 // first conversion is ObjectInit's standard conversion (which is
6495 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006496 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006497 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006498 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006499 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006500 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006501 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006502 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006503 = Candidate.Conversions[0].UserDefined.Before;
6504 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6505
Mike Stump11289f42009-09-09 15:08:12 +00006506 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006507 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006508
6509 // (C++ 13.3.2p2): A candidate function having fewer than m
6510 // parameters is viable only if it has an ellipsis in its parameter
6511 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006512 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006513 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006514 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006515 return;
6516 }
6517
6518 // Function types don't have any default arguments, so just check if
6519 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006520 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006521 // Not enough arguments.
6522 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006523 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006524 return;
6525 }
6526
6527 // Determine the implicit conversion sequences for each of the
6528 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006529 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006530 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006531 // (C++ 13.3.2p3): for F to be a viable function, there shall
6532 // exist for each argument an implicit conversion sequence
6533 // (13.3.3.1) that converts that argument to the corresponding
6534 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006535 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006536 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006537 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006538 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006539 /*InOverloadResolution=*/false,
6540 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006541 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006542 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006543 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006544 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006545 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006546 }
6547 } else {
6548 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6549 // argument for which there is no corresponding parameter is
6550 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006551 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006552 }
6553 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006554
Craig Topper5fc8fc22014-08-27 06:28:36 +00006555 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006556 Candidate.Viable = false;
6557 Candidate.FailureKind = ovl_fail_enable_if;
6558 Candidate.DeductionFailure.Data = FailedAttr;
6559 return;
6560 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006561}
6562
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006563/// \brief Add overload candidates for overloaded operators that are
6564/// member functions.
6565///
6566/// Add the overloaded operator candidates that are member functions
6567/// for the operator Op that was used in an operator expression such
6568/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6569/// CandidateSet will store the added overload candidates. (C++
6570/// [over.match.oper]).
6571void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6572 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006573 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006574 OverloadCandidateSet& CandidateSet,
6575 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006576 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6577
6578 // C++ [over.match.oper]p3:
6579 // For a unary operator @ with an operand of a type whose
6580 // cv-unqualified version is T1, and for a binary operator @ with
6581 // a left operand of a type whose cv-unqualified version is T1 and
6582 // a right operand of a type whose cv-unqualified version is T2,
6583 // three sets of candidate functions, designated member
6584 // candidates, non-member candidates and built-in candidates, are
6585 // constructed as follows:
6586 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006587
Richard Smith0feaf0c2013-04-20 12:41:22 +00006588 // -- If T1 is a complete class type or a class currently being
6589 // defined, the set of member candidates is the result of the
6590 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6591 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006592 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006593 // Complete the type if it can be completed.
6594 RequireCompleteType(OpLoc, T1, 0);
6595 // If the type is neither complete nor being defined, bail out now.
6596 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006597 return;
Mike Stump11289f42009-09-09 15:08:12 +00006598
John McCall27b18f82009-11-17 02:14:36 +00006599 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6600 LookupQualifiedName(Operators, T1Rec->getDecl());
6601 Operators.suppressDiagnostics();
6602
Mike Stump11289f42009-09-09 15:08:12 +00006603 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006604 OperEnd = Operators.end();
6605 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006606 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006607 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006608 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006609 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006610 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006611 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006612 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006613}
6614
Douglas Gregora11693b2008-11-12 17:17:38 +00006615/// AddBuiltinCandidate - Add a candidate for a built-in
6616/// operator. ResultTy and ParamTys are the result and parameter types
6617/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006618/// arguments being passed to the candidate. IsAssignmentOperator
6619/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006620/// operator. NumContextualBoolArguments is the number of arguments
6621/// (at the beginning of the argument list) that will be contextually
6622/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006623void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006624 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006625 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006626 bool IsAssignmentOperator,
6627 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006628 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006629 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006630
Douglas Gregora11693b2008-11-12 17:17:38 +00006631 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006632 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006633 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6634 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006635 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006636 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006637 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006638 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006639 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6640
6641 // Determine the implicit conversion sequences for each of the
6642 // arguments.
6643 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006644 Candidate.ExplicitCallArguments = Args.size();
6645 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006646 // C++ [over.match.oper]p4:
6647 // For the built-in assignment operators, conversions of the
6648 // left operand are restricted as follows:
6649 // -- no temporaries are introduced to hold the left operand, and
6650 // -- no user-defined conversions are applied to the left
6651 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006652 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006653 //
6654 // We block these conversions by turning off user-defined
6655 // conversions, since that is the only way that initialization of
6656 // a reference to a non-class type can occur from something that
6657 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006658 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006659 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006660 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006661 Candidate.Conversions[ArgIdx]
6662 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006663 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006664 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006665 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006666 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006667 /*InOverloadResolution=*/false,
6668 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006669 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006670 }
John McCall0d1da222010-01-12 00:44:57 +00006671 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006672 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006673 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006674 break;
6675 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006676 }
6677}
6678
Craig Toppercd7b0332013-07-01 06:29:40 +00006679namespace {
6680
Douglas Gregora11693b2008-11-12 17:17:38 +00006681/// BuiltinCandidateTypeSet - A set of types that will be used for the
6682/// candidate operator functions for built-in operators (C++
6683/// [over.built]). The types are separated into pointer types and
6684/// enumeration types.
6685class BuiltinCandidateTypeSet {
6686 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006687 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006688
6689 /// PointerTypes - The set of pointer types that will be used in the
6690 /// built-in candidates.
6691 TypeSet PointerTypes;
6692
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006693 /// MemberPointerTypes - The set of member pointer types that will be
6694 /// used in the built-in candidates.
6695 TypeSet MemberPointerTypes;
6696
Douglas Gregora11693b2008-11-12 17:17:38 +00006697 /// EnumerationTypes - The set of enumeration types that will be
6698 /// used in the built-in candidates.
6699 TypeSet EnumerationTypes;
6700
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006701 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006702 /// candidates.
6703 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006704
6705 /// \brief A flag indicating non-record types are viable candidates
6706 bool HasNonRecordTypes;
6707
6708 /// \brief A flag indicating whether either arithmetic or enumeration types
6709 /// were present in the candidate set.
6710 bool HasArithmeticOrEnumeralTypes;
6711
Douglas Gregor80af3132011-05-21 23:15:46 +00006712 /// \brief A flag indicating whether the nullptr type was present in the
6713 /// candidate set.
6714 bool HasNullPtrType;
6715
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006716 /// Sema - The semantic analysis instance where we are building the
6717 /// candidate type set.
6718 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006719
Douglas Gregora11693b2008-11-12 17:17:38 +00006720 /// Context - The AST context in which we will build the type sets.
6721 ASTContext &Context;
6722
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006723 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6724 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006725 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006726
6727public:
6728 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006729 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006730
Mike Stump11289f42009-09-09 15:08:12 +00006731 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006732 : HasNonRecordTypes(false),
6733 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006734 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006735 SemaRef(SemaRef),
6736 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006737
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006738 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006739 SourceLocation Loc,
6740 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006741 bool AllowExplicitConversions,
6742 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006743
6744 /// pointer_begin - First pointer type found;
6745 iterator pointer_begin() { return PointerTypes.begin(); }
6746
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006747 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006748 iterator pointer_end() { return PointerTypes.end(); }
6749
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006750 /// member_pointer_begin - First member pointer type found;
6751 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6752
6753 /// member_pointer_end - Past the last member pointer type found;
6754 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6755
Douglas Gregora11693b2008-11-12 17:17:38 +00006756 /// enumeration_begin - First enumeration type found;
6757 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6758
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006759 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006760 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006761
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006762 iterator vector_begin() { return VectorTypes.begin(); }
6763 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006764
6765 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6766 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006767 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006768};
6769
Craig Toppercd7b0332013-07-01 06:29:40 +00006770} // end anonymous namespace
6771
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006772/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006773/// the set of pointer types along with any more-qualified variants of
6774/// that type. For example, if @p Ty is "int const *", this routine
6775/// will add "int const *", "int const volatile *", "int const
6776/// restrict *", and "int const volatile restrict *" to the set of
6777/// pointer types. Returns true if the add of @p Ty itself succeeded,
6778/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006779///
6780/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006781bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006782BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6783 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006784
Douglas Gregora11693b2008-11-12 17:17:38 +00006785 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006786 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006787 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006788
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006789 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006790 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006791 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006792 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006793 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6794 PointeeTy = PTy->getPointeeType();
6795 buildObjCPtr = true;
6796 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006797 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006798 }
6799
Sebastian Redl4990a632009-11-18 20:39:26 +00006800 // Don't add qualified variants of arrays. For one, they're not allowed
6801 // (the qualifier would sink to the element type), and for another, the
6802 // only overload situation where it matters is subscript or pointer +- int,
6803 // and those shouldn't have qualifier variants anyway.
6804 if (PointeeTy->isArrayType())
6805 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006806
John McCall8ccfcb52009-09-24 19:53:00 +00006807 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006808 bool hasVolatile = VisibleQuals.hasVolatile();
6809 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006810
John McCall8ccfcb52009-09-24 19:53:00 +00006811 // Iterate through all strict supersets of BaseCVR.
6812 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6813 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006814 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006815 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006816
6817 // Skip over restrict if no restrict found anywhere in the types, or if
6818 // the type cannot be restrict-qualified.
6819 if ((CVR & Qualifiers::Restrict) &&
6820 (!hasRestrict ||
6821 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6822 continue;
6823
6824 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006825 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006826
6827 // Build qualified pointer type.
6828 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006829 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006830 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006831 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006832 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6833
6834 // Insert qualified pointer type.
6835 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006836 }
6837
6838 return true;
6839}
6840
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006841/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6842/// to the set of pointer types along with any more-qualified variants of
6843/// that type. For example, if @p Ty is "int const *", this routine
6844/// will add "int const *", "int const volatile *", "int const
6845/// restrict *", and "int const volatile restrict *" to the set of
6846/// pointer types. Returns true if the add of @p Ty itself succeeded,
6847/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006848///
6849/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006850bool
6851BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6852 QualType Ty) {
6853 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006854 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006855 return false;
6856
John McCall8ccfcb52009-09-24 19:53:00 +00006857 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6858 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006859
John McCall8ccfcb52009-09-24 19:53:00 +00006860 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006861 // Don't add qualified variants of arrays. For one, they're not allowed
6862 // (the qualifier would sink to the element type), and for another, the
6863 // only overload situation where it matters is subscript or pointer +- int,
6864 // and those shouldn't have qualifier variants anyway.
6865 if (PointeeTy->isArrayType())
6866 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006867 const Type *ClassTy = PointerTy->getClass();
6868
6869 // Iterate through all strict supersets of the pointee type's CVR
6870 // qualifiers.
6871 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6872 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6873 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006874
John McCall8ccfcb52009-09-24 19:53:00 +00006875 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006876 MemberPointerTypes.insert(
6877 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006878 }
6879
6880 return true;
6881}
6882
Douglas Gregora11693b2008-11-12 17:17:38 +00006883/// AddTypesConvertedFrom - Add each of the types to which the type @p
6884/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006885/// primarily interested in pointer types and enumeration types. We also
6886/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006887/// AllowUserConversions is true if we should look at the conversion
6888/// functions of a class type, and AllowExplicitConversions if we
6889/// should also include the explicit conversion functions of a class
6890/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006891void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006892BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006893 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006894 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006895 bool AllowExplicitConversions,
6896 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006897 // Only deal with canonical types.
6898 Ty = Context.getCanonicalType(Ty);
6899
6900 // Look through reference types; they aren't part of the type of an
6901 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006902 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006903 Ty = RefTy->getPointeeType();
6904
John McCall33ddac02011-01-19 10:06:00 +00006905 // If we're dealing with an array type, decay to the pointer.
6906 if (Ty->isArrayType())
6907 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6908
6909 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006910 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006911
Chandler Carruth00a38332010-12-13 01:44:01 +00006912 // Flag if we ever add a non-record type.
6913 const RecordType *TyRec = Ty->getAs<RecordType>();
6914 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6915
Chandler Carruth00a38332010-12-13 01:44:01 +00006916 // Flag if we encounter an arithmetic type.
6917 HasArithmeticOrEnumeralTypes =
6918 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6919
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006920 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6921 PointerTypes.insert(Ty);
6922 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006923 // Insert our type, and its more-qualified variants, into the set
6924 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006925 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006926 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006927 } else if (Ty->isMemberPointerType()) {
6928 // Member pointers are far easier, since the pointee can't be converted.
6929 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6930 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006931 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006932 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006933 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006934 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006935 // We treat vector types as arithmetic types in many contexts as an
6936 // extension.
6937 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006938 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006939 } else if (Ty->isNullPtrType()) {
6940 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006941 } else if (AllowUserConversions && TyRec) {
6942 // No conversion functions in incomplete types.
6943 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6944 return;
Mike Stump11289f42009-09-09 15:08:12 +00006945
Chandler Carruth00a38332010-12-13 01:44:01 +00006946 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006947 std::pair<CXXRecordDecl::conversion_iterator,
6948 CXXRecordDecl::conversion_iterator>
6949 Conversions = ClassDecl->getVisibleConversionFunctions();
6950 for (CXXRecordDecl::conversion_iterator
6951 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006952 NamedDecl *D = I.getDecl();
6953 if (isa<UsingShadowDecl>(D))
6954 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006955
Chandler Carruth00a38332010-12-13 01:44:01 +00006956 // Skip conversion function templates; they don't tell us anything
6957 // about which builtin types we can convert to.
6958 if (isa<FunctionTemplateDecl>(D))
6959 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006960
Chandler Carruth00a38332010-12-13 01:44:01 +00006961 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6962 if (AllowExplicitConversions || !Conv->isExplicit()) {
6963 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6964 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006965 }
6966 }
6967 }
6968}
6969
Douglas Gregor84605ae2009-08-24 13:43:27 +00006970/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6971/// the volatile- and non-volatile-qualified assignment operators for the
6972/// given type to the candidate set.
6973static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6974 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006975 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006976 OverloadCandidateSet &CandidateSet) {
6977 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006978
Douglas Gregor84605ae2009-08-24 13:43:27 +00006979 // T& operator=(T&, T)
6980 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6981 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006982 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006983 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006984
Douglas Gregor84605ae2009-08-24 13:43:27 +00006985 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6986 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006987 ParamTypes[0]
6988 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006989 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006990 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006991 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006992 }
6993}
Mike Stump11289f42009-09-09 15:08:12 +00006994
Sebastian Redl1054fae2009-10-25 17:03:50 +00006995/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6996/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006997static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6998 Qualifiers VRQuals;
6999 const RecordType *TyRec;
7000 if (const MemberPointerType *RHSMPType =
7001 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007002 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007003 else
7004 TyRec = ArgExpr->getType()->getAs<RecordType>();
7005 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007006 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007007 VRQuals.addVolatile();
7008 VRQuals.addRestrict();
7009 return VRQuals;
7010 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007011
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007012 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007013 if (!ClassDecl->hasDefinition())
7014 return VRQuals;
7015
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00007016 std::pair<CXXRecordDecl::conversion_iterator,
7017 CXXRecordDecl::conversion_iterator>
7018 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007019
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00007020 for (CXXRecordDecl::conversion_iterator
7021 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00007022 NamedDecl *D = I.getDecl();
7023 if (isa<UsingShadowDecl>(D))
7024 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7025 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007026 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7027 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7028 CanTy = ResTypeRef->getPointeeType();
7029 // Need to go down the pointer/mempointer chain and add qualifiers
7030 // as see them.
7031 bool done = false;
7032 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007033 if (CanTy.isRestrictQualified())
7034 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007035 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7036 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007037 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007038 CanTy->getAs<MemberPointerType>())
7039 CanTy = ResTypeMPtr->getPointeeType();
7040 else
7041 done = true;
7042 if (CanTy.isVolatileQualified())
7043 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007044 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7045 return VRQuals;
7046 }
7047 }
7048 }
7049 return VRQuals;
7050}
John McCall52872982010-11-13 05:51:15 +00007051
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007052namespace {
John McCall52872982010-11-13 05:51:15 +00007053
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007054/// \brief Helper class to manage the addition of builtin operator overload
7055/// candidates. It provides shared state and utility methods used throughout
7056/// the process, as well as a helper method to add each group of builtin
7057/// operator overloads from the standard to a candidate set.
7058class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007059 // Common instance state available to all overload candidate addition methods.
7060 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007061 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007062 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007063 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007064 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007065 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007066
Chandler Carruthc6586e52010-12-12 10:35:00 +00007067 // Define some constants used to index and iterate over the arithemetic types
7068 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007069 // The "promoted arithmetic types" are the arithmetic
7070 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007071 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007072 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007073 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007074 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007075 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007076 LastPromotedArithmeticType = 11;
7077 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007078
Chandler Carruthc6586e52010-12-12 10:35:00 +00007079 /// \brief Get the canonical type for a given arithmetic type index.
7080 CanQualType getArithmeticType(unsigned index) {
7081 assert(index < NumArithmeticTypes);
7082 static CanQualType ASTContext::* const
7083 ArithmeticTypes[NumArithmeticTypes] = {
7084 // Start of promoted types.
7085 &ASTContext::FloatTy,
7086 &ASTContext::DoubleTy,
7087 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007088
Chandler Carruthc6586e52010-12-12 10:35:00 +00007089 // Start of integral types.
7090 &ASTContext::IntTy,
7091 &ASTContext::LongTy,
7092 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007093 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007094 &ASTContext::UnsignedIntTy,
7095 &ASTContext::UnsignedLongTy,
7096 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007097 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007098 // End of promoted types.
7099
7100 &ASTContext::BoolTy,
7101 &ASTContext::CharTy,
7102 &ASTContext::WCharTy,
7103 &ASTContext::Char16Ty,
7104 &ASTContext::Char32Ty,
7105 &ASTContext::SignedCharTy,
7106 &ASTContext::ShortTy,
7107 &ASTContext::UnsignedCharTy,
7108 &ASTContext::UnsignedShortTy,
7109 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007110 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007111 };
7112 return S.Context.*ArithmeticTypes[index];
7113 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007114
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007115 /// \brief Gets the canonical type resulting from the usual arithemetic
7116 /// converions for the given arithmetic types.
7117 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7118 // Accelerator table for performing the usual arithmetic conversions.
7119 // The rules are basically:
7120 // - if either is floating-point, use the wider floating-point
7121 // - if same signedness, use the higher rank
7122 // - if same size, use unsigned of the higher rank
7123 // - use the larger type
7124 // These rules, together with the axiom that higher ranks are
7125 // never smaller, are sufficient to precompute all of these results
7126 // *except* when dealing with signed types of higher rank.
7127 // (we could precompute SLL x UI for all known platforms, but it's
7128 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007129 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007130 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007131 Dep=-1,
7132 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007133 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007134 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007135 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007136/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7137/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7138/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7139/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7140/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7141/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7142/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7143/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7144/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7145/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7146/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007147 };
7148
7149 assert(L < LastPromotedArithmeticType);
7150 assert(R < LastPromotedArithmeticType);
7151 int Idx = ConversionsTable[L][R];
7152
7153 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007154 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007155
7156 // Slow path: we need to compare widths.
7157 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007158 CanQualType LT = getArithmeticType(L),
7159 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007160 unsigned LW = S.Context.getIntWidth(LT),
7161 RW = S.Context.getIntWidth(RT);
7162
7163 // If they're different widths, use the signed type.
7164 if (LW > RW) return LT;
7165 else if (LW < RW) return RT;
7166
7167 // Otherwise, use the unsigned type of the signed type's rank.
7168 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7169 assert(L == SLL || R == SLL);
7170 return S.Context.UnsignedLongLongTy;
7171 }
7172
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007173 /// \brief Helper method to factor out the common pattern of adding overloads
7174 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007175 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007176 bool HasVolatile,
7177 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007178 QualType ParamTypes[2] = {
7179 S.Context.getLValueReferenceType(CandidateTy),
7180 S.Context.IntTy
7181 };
7182
7183 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007184 if (Args.size() == 1)
7185 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007186 else
Richard Smithe54c3072013-05-05 15:51:06 +00007187 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007188
7189 // Use a heuristic to reduce number of builtin candidates in the set:
7190 // add volatile version only if there are conversions to a volatile type.
7191 if (HasVolatile) {
7192 ParamTypes[0] =
7193 S.Context.getLValueReferenceType(
7194 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007195 if (Args.size() == 1)
7196 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007197 else
Richard Smithe54c3072013-05-05 15:51:06 +00007198 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007199 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007200
7201 // Add restrict version only if there are conversions to a restrict type
7202 // and our candidate type is a non-restrict-qualified pointer.
7203 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7204 !CandidateTy.isRestrictQualified()) {
7205 ParamTypes[0]
7206 = S.Context.getLValueReferenceType(
7207 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007208 if (Args.size() == 1)
7209 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007210 else
Richard Smithe54c3072013-05-05 15:51:06 +00007211 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007212
7213 if (HasVolatile) {
7214 ParamTypes[0]
7215 = S.Context.getLValueReferenceType(
7216 S.Context.getCVRQualifiedType(CandidateTy,
7217 (Qualifiers::Volatile |
7218 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007219 if (Args.size() == 1)
7220 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007221 else
Richard Smithe54c3072013-05-05 15:51:06 +00007222 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007223 }
7224 }
7225
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007226 }
7227
7228public:
7229 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007230 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007231 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007232 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007233 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007234 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007235 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007236 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007237 HasArithmeticOrEnumeralCandidateType(
7238 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007239 CandidateTypes(CandidateTypes),
7240 CandidateSet(CandidateSet) {
7241 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007242 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007243 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007244 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007245 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007246 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007247 assert(getArithmeticType(FirstPromotedArithmeticType)
7248 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007249 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007250 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007251 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007252 "Invalid last promoted arithmetic type");
7253 }
7254
7255 // C++ [over.built]p3:
7256 //
7257 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7258 // is either volatile or empty, there exist candidate operator
7259 // functions of the form
7260 //
7261 // VQ T& operator++(VQ T&);
7262 // T operator++(VQ T&, int);
7263 //
7264 // C++ [over.built]p4:
7265 //
7266 // For every pair (T, VQ), where T is an arithmetic type other
7267 // than bool, and VQ is either volatile or empty, there exist
7268 // candidate operator functions of the form
7269 //
7270 // VQ T& operator--(VQ T&);
7271 // T operator--(VQ T&, int);
7272 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007273 if (!HasArithmeticOrEnumeralCandidateType)
7274 return;
7275
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007276 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7277 Arith < NumArithmeticTypes; ++Arith) {
7278 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007279 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007280 VisibleTypeConversionsQuals.hasVolatile(),
7281 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007282 }
7283 }
7284
7285 // C++ [over.built]p5:
7286 //
7287 // For every pair (T, VQ), where T is a cv-qualified or
7288 // cv-unqualified object type, and VQ is either volatile or
7289 // empty, there exist candidate operator functions of the form
7290 //
7291 // T*VQ& operator++(T*VQ&);
7292 // T*VQ& operator--(T*VQ&);
7293 // T* operator++(T*VQ&, int);
7294 // T* operator--(T*VQ&, int);
7295 void addPlusPlusMinusMinusPointerOverloads() {
7296 for (BuiltinCandidateTypeSet::iterator
7297 Ptr = CandidateTypes[0].pointer_begin(),
7298 PtrEnd = CandidateTypes[0].pointer_end();
7299 Ptr != PtrEnd; ++Ptr) {
7300 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007301 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007302 continue;
7303
7304 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007305 (!(*Ptr).isVolatileQualified() &&
7306 VisibleTypeConversionsQuals.hasVolatile()),
7307 (!(*Ptr).isRestrictQualified() &&
7308 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007309 }
7310 }
7311
7312 // C++ [over.built]p6:
7313 // For every cv-qualified or cv-unqualified object type T, there
7314 // exist candidate operator functions of the form
7315 //
7316 // T& operator*(T*);
7317 //
7318 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007319 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007320 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007321 // T& operator*(T*);
7322 void addUnaryStarPointerOverloads() {
7323 for (BuiltinCandidateTypeSet::iterator
7324 Ptr = CandidateTypes[0].pointer_begin(),
7325 PtrEnd = CandidateTypes[0].pointer_end();
7326 Ptr != PtrEnd; ++Ptr) {
7327 QualType ParamTy = *Ptr;
7328 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007329 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7330 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007331
Douglas Gregor02824322011-01-26 19:30:28 +00007332 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7333 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7334 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007335
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007336 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007337 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007338 }
7339 }
7340
7341 // C++ [over.built]p9:
7342 // For every promoted arithmetic type T, there exist candidate
7343 // operator functions of the form
7344 //
7345 // T operator+(T);
7346 // T operator-(T);
7347 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007348 if (!HasArithmeticOrEnumeralCandidateType)
7349 return;
7350
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007351 for (unsigned Arith = FirstPromotedArithmeticType;
7352 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007353 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007354 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007355 }
7356
7357 // Extension: We also add these operators for vector types.
7358 for (BuiltinCandidateTypeSet::iterator
7359 Vec = CandidateTypes[0].vector_begin(),
7360 VecEnd = CandidateTypes[0].vector_end();
7361 Vec != VecEnd; ++Vec) {
7362 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007363 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007364 }
7365 }
7366
7367 // C++ [over.built]p8:
7368 // For every type T, there exist candidate operator functions of
7369 // the form
7370 //
7371 // T* operator+(T*);
7372 void addUnaryPlusPointerOverloads() {
7373 for (BuiltinCandidateTypeSet::iterator
7374 Ptr = CandidateTypes[0].pointer_begin(),
7375 PtrEnd = CandidateTypes[0].pointer_end();
7376 Ptr != PtrEnd; ++Ptr) {
7377 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007378 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007379 }
7380 }
7381
7382 // C++ [over.built]p10:
7383 // For every promoted integral type T, there exist candidate
7384 // operator functions of the form
7385 //
7386 // T operator~(T);
7387 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007388 if (!HasArithmeticOrEnumeralCandidateType)
7389 return;
7390
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007391 for (unsigned Int = FirstPromotedIntegralType;
7392 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007393 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007394 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007395 }
7396
7397 // Extension: We also add this operator for vector types.
7398 for (BuiltinCandidateTypeSet::iterator
7399 Vec = CandidateTypes[0].vector_begin(),
7400 VecEnd = CandidateTypes[0].vector_end();
7401 Vec != VecEnd; ++Vec) {
7402 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007403 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007404 }
7405 }
7406
7407 // C++ [over.match.oper]p16:
7408 // For every pointer to member type T, there exist candidate operator
7409 // functions of the form
7410 //
7411 // bool operator==(T,T);
7412 // bool operator!=(T,T);
7413 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7414 /// Set of (canonical) types that we've already handled.
7415 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7416
Richard Smithe54c3072013-05-05 15:51:06 +00007417 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007418 for (BuiltinCandidateTypeSet::iterator
7419 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7420 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7421 MemPtr != MemPtrEnd;
7422 ++MemPtr) {
7423 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007424 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007425 continue;
7426
7427 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007428 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007429 }
7430 }
7431 }
7432
7433 // C++ [over.built]p15:
7434 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007435 // For every T, where T is an enumeration type, a pointer type, or
7436 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007437 //
7438 // bool operator<(T, T);
7439 // bool operator>(T, T);
7440 // bool operator<=(T, T);
7441 // bool operator>=(T, T);
7442 // bool operator==(T, T);
7443 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007444 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007445 // C++ [over.match.oper]p3:
7446 // [...]the built-in candidates include all of the candidate operator
7447 // functions defined in 13.6 that, compared to the given operator, [...]
7448 // do not have the same parameter-type-list as any non-template non-member
7449 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007450 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007451 // Note that in practice, this only affects enumeration types because there
7452 // aren't any built-in candidates of record type, and a user-defined operator
7453 // must have an operand of record or enumeration type. Also, the only other
7454 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007455 // cannot be overloaded for enumeration types, so this is the only place
7456 // where we must suppress candidates like this.
7457 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7458 UserDefinedBinaryOperators;
7459
Richard Smithe54c3072013-05-05 15:51:06 +00007460 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007461 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7462 CandidateTypes[ArgIdx].enumeration_end()) {
7463 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7464 CEnd = CandidateSet.end();
7465 C != CEnd; ++C) {
7466 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7467 continue;
7468
Eli Friedman14f082b2012-09-18 21:52:24 +00007469 if (C->Function->isFunctionTemplateSpecialization())
7470 continue;
7471
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007472 QualType FirstParamType =
7473 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7474 QualType SecondParamType =
7475 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7476
7477 // Skip if either parameter isn't of enumeral type.
7478 if (!FirstParamType->isEnumeralType() ||
7479 !SecondParamType->isEnumeralType())
7480 continue;
7481
7482 // Add this operator to the set of known user-defined operators.
7483 UserDefinedBinaryOperators.insert(
7484 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7485 S.Context.getCanonicalType(SecondParamType)));
7486 }
7487 }
7488 }
7489
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007490 /// Set of (canonical) types that we've already handled.
7491 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7492
Richard Smithe54c3072013-05-05 15:51:06 +00007493 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007494 for (BuiltinCandidateTypeSet::iterator
7495 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7496 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7497 Ptr != PtrEnd; ++Ptr) {
7498 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007499 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007500 continue;
7501
7502 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007503 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007504 }
7505 for (BuiltinCandidateTypeSet::iterator
7506 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7507 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7508 Enum != EnumEnd; ++Enum) {
7509 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7510
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007511 // Don't add the same builtin candidate twice, or if a user defined
7512 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007513 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007514 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7515 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007516 continue;
7517
7518 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007519 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007520 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007521
7522 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7523 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007524 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007525 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007526 NullPtrTy))) {
7527 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007528 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007529 CandidateSet);
7530 }
7531 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007532 }
7533 }
7534
7535 // C++ [over.built]p13:
7536 //
7537 // For every cv-qualified or cv-unqualified object type T
7538 // there exist candidate operator functions of the form
7539 //
7540 // T* operator+(T*, ptrdiff_t);
7541 // T& operator[](T*, ptrdiff_t); [BELOW]
7542 // T* operator-(T*, ptrdiff_t);
7543 // T* operator+(ptrdiff_t, T*);
7544 // T& operator[](ptrdiff_t, T*); [BELOW]
7545 //
7546 // C++ [over.built]p14:
7547 //
7548 // For every T, where T is a pointer to object type, there
7549 // exist candidate operator functions of the form
7550 //
7551 // ptrdiff_t operator-(T, T);
7552 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7553 /// Set of (canonical) types that we've already handled.
7554 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7555
7556 for (int Arg = 0; Arg < 2; ++Arg) {
7557 QualType AsymetricParamTypes[2] = {
7558 S.Context.getPointerDiffType(),
7559 S.Context.getPointerDiffType(),
7560 };
7561 for (BuiltinCandidateTypeSet::iterator
7562 Ptr = CandidateTypes[Arg].pointer_begin(),
7563 PtrEnd = CandidateTypes[Arg].pointer_end();
7564 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007565 QualType PointeeTy = (*Ptr)->getPointeeType();
7566 if (!PointeeTy->isObjectType())
7567 continue;
7568
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007569 AsymetricParamTypes[Arg] = *Ptr;
7570 if (Arg == 0 || Op == OO_Plus) {
7571 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7572 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007573 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007574 }
7575 if (Op == OO_Minus) {
7576 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007577 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007578 continue;
7579
7580 QualType ParamTypes[2] = { *Ptr, *Ptr };
7581 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007582 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007583 }
7584 }
7585 }
7586 }
7587
7588 // C++ [over.built]p12:
7589 //
7590 // For every pair of promoted arithmetic types L and R, there
7591 // exist candidate operator functions of the form
7592 //
7593 // LR operator*(L, R);
7594 // LR operator/(L, R);
7595 // LR operator+(L, R);
7596 // LR operator-(L, R);
7597 // bool operator<(L, R);
7598 // bool operator>(L, R);
7599 // bool operator<=(L, R);
7600 // bool operator>=(L, R);
7601 // bool operator==(L, R);
7602 // bool operator!=(L, R);
7603 //
7604 // where LR is the result of the usual arithmetic conversions
7605 // between types L and R.
7606 //
7607 // C++ [over.built]p24:
7608 //
7609 // For every pair of promoted arithmetic types L and R, there exist
7610 // candidate operator functions of the form
7611 //
7612 // LR operator?(bool, L, R);
7613 //
7614 // where LR is the result of the usual arithmetic conversions
7615 // between types L and R.
7616 // Our candidates ignore the first parameter.
7617 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007618 if (!HasArithmeticOrEnumeralCandidateType)
7619 return;
7620
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007621 for (unsigned Left = FirstPromotedArithmeticType;
7622 Left < LastPromotedArithmeticType; ++Left) {
7623 for (unsigned Right = FirstPromotedArithmeticType;
7624 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007625 QualType LandR[2] = { getArithmeticType(Left),
7626 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007627 QualType Result =
7628 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007629 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007630 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007631 }
7632 }
7633
7634 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7635 // conditional operator for vector types.
7636 for (BuiltinCandidateTypeSet::iterator
7637 Vec1 = CandidateTypes[0].vector_begin(),
7638 Vec1End = CandidateTypes[0].vector_end();
7639 Vec1 != Vec1End; ++Vec1) {
7640 for (BuiltinCandidateTypeSet::iterator
7641 Vec2 = CandidateTypes[1].vector_begin(),
7642 Vec2End = CandidateTypes[1].vector_end();
7643 Vec2 != Vec2End; ++Vec2) {
7644 QualType LandR[2] = { *Vec1, *Vec2 };
7645 QualType Result = S.Context.BoolTy;
7646 if (!isComparison) {
7647 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7648 Result = *Vec1;
7649 else
7650 Result = *Vec2;
7651 }
7652
Richard Smithe54c3072013-05-05 15:51:06 +00007653 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007654 }
7655 }
7656 }
7657
7658 // C++ [over.built]p17:
7659 //
7660 // For every pair of promoted integral types L and R, there
7661 // exist candidate operator functions of the form
7662 //
7663 // LR operator%(L, R);
7664 // LR operator&(L, R);
7665 // LR operator^(L, R);
7666 // LR operator|(L, R);
7667 // L operator<<(L, R);
7668 // L operator>>(L, R);
7669 //
7670 // where LR is the result of the usual arithmetic conversions
7671 // between types L and R.
7672 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007673 if (!HasArithmeticOrEnumeralCandidateType)
7674 return;
7675
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007676 for (unsigned Left = FirstPromotedIntegralType;
7677 Left < LastPromotedIntegralType; ++Left) {
7678 for (unsigned Right = FirstPromotedIntegralType;
7679 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007680 QualType LandR[2] = { getArithmeticType(Left),
7681 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007682 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7683 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007684 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007685 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007686 }
7687 }
7688 }
7689
7690 // C++ [over.built]p20:
7691 //
7692 // For every pair (T, VQ), where T is an enumeration or
7693 // pointer to member type and VQ is either volatile or
7694 // empty, there exist candidate operator functions of the form
7695 //
7696 // VQ T& operator=(VQ T&, T);
7697 void addAssignmentMemberPointerOrEnumeralOverloads() {
7698 /// Set of (canonical) types that we've already handled.
7699 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7700
7701 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7702 for (BuiltinCandidateTypeSet::iterator
7703 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7704 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7705 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007706 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007707 continue;
7708
Richard Smithe54c3072013-05-05 15:51:06 +00007709 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007710 }
7711
7712 for (BuiltinCandidateTypeSet::iterator
7713 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7714 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7715 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007716 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007717 continue;
7718
Richard Smithe54c3072013-05-05 15:51:06 +00007719 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007720 }
7721 }
7722 }
7723
7724 // C++ [over.built]p19:
7725 //
7726 // For every pair (T, VQ), where T is any type and VQ is either
7727 // volatile or empty, there exist candidate operator functions
7728 // of the form
7729 //
7730 // T*VQ& operator=(T*VQ&, T*);
7731 //
7732 // C++ [over.built]p21:
7733 //
7734 // For every pair (T, VQ), where T is a cv-qualified or
7735 // cv-unqualified object type and VQ is either volatile or
7736 // empty, there exist candidate operator functions of the form
7737 //
7738 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7739 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7740 void addAssignmentPointerOverloads(bool isEqualOp) {
7741 /// Set of (canonical) types that we've already handled.
7742 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7743
7744 for (BuiltinCandidateTypeSet::iterator
7745 Ptr = CandidateTypes[0].pointer_begin(),
7746 PtrEnd = CandidateTypes[0].pointer_end();
7747 Ptr != PtrEnd; ++Ptr) {
7748 // If this is operator=, keep track of the builtin candidates we added.
7749 if (isEqualOp)
7750 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007751 else if (!(*Ptr)->getPointeeType()->isObjectType())
7752 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007753
7754 // non-volatile version
7755 QualType ParamTypes[2] = {
7756 S.Context.getLValueReferenceType(*Ptr),
7757 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7758 };
Richard Smithe54c3072013-05-05 15:51:06 +00007759 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007760 /*IsAssigmentOperator=*/ isEqualOp);
7761
Douglas Gregor5bee2582012-06-04 00:15:09 +00007762 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7763 VisibleTypeConversionsQuals.hasVolatile();
7764 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007765 // volatile version
7766 ParamTypes[0] =
7767 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007768 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007769 /*IsAssigmentOperator=*/isEqualOp);
7770 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007771
7772 if (!(*Ptr).isRestrictQualified() &&
7773 VisibleTypeConversionsQuals.hasRestrict()) {
7774 // restrict version
7775 ParamTypes[0]
7776 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007777 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007778 /*IsAssigmentOperator=*/isEqualOp);
7779
7780 if (NeedVolatile) {
7781 // volatile restrict version
7782 ParamTypes[0]
7783 = S.Context.getLValueReferenceType(
7784 S.Context.getCVRQualifiedType(*Ptr,
7785 (Qualifiers::Volatile |
7786 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007787 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007788 /*IsAssigmentOperator=*/isEqualOp);
7789 }
7790 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007791 }
7792
7793 if (isEqualOp) {
7794 for (BuiltinCandidateTypeSet::iterator
7795 Ptr = CandidateTypes[1].pointer_begin(),
7796 PtrEnd = CandidateTypes[1].pointer_end();
7797 Ptr != PtrEnd; ++Ptr) {
7798 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007799 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007800 continue;
7801
Chandler Carruth8e543b32010-12-12 08:17:55 +00007802 QualType ParamTypes[2] = {
7803 S.Context.getLValueReferenceType(*Ptr),
7804 *Ptr,
7805 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007806
7807 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007808 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007809 /*IsAssigmentOperator=*/true);
7810
Douglas Gregor5bee2582012-06-04 00:15:09 +00007811 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7812 VisibleTypeConversionsQuals.hasVolatile();
7813 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007814 // volatile version
7815 ParamTypes[0] =
7816 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007817 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7818 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007819 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007820
7821 if (!(*Ptr).isRestrictQualified() &&
7822 VisibleTypeConversionsQuals.hasRestrict()) {
7823 // restrict version
7824 ParamTypes[0]
7825 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007826 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7827 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007828
7829 if (NeedVolatile) {
7830 // volatile restrict version
7831 ParamTypes[0]
7832 = S.Context.getLValueReferenceType(
7833 S.Context.getCVRQualifiedType(*Ptr,
7834 (Qualifiers::Volatile |
7835 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007836 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7837 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007838 }
7839 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007840 }
7841 }
7842 }
7843
7844 // C++ [over.built]p18:
7845 //
7846 // For every triple (L, VQ, R), where L is an arithmetic type,
7847 // VQ is either volatile or empty, and R is a promoted
7848 // arithmetic type, there exist candidate operator functions of
7849 // the form
7850 //
7851 // VQ L& operator=(VQ L&, R);
7852 // VQ L& operator*=(VQ L&, R);
7853 // VQ L& operator/=(VQ L&, R);
7854 // VQ L& operator+=(VQ L&, R);
7855 // VQ L& operator-=(VQ L&, R);
7856 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007857 if (!HasArithmeticOrEnumeralCandidateType)
7858 return;
7859
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007860 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7861 for (unsigned Right = FirstPromotedArithmeticType;
7862 Right < LastPromotedArithmeticType; ++Right) {
7863 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007864 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007865
7866 // Add this built-in operator as a candidate (VQ is empty).
7867 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007868 S.Context.getLValueReferenceType(getArithmeticType(Left));
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] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007875 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007876 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007877 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007878 /*IsAssigmentOperator=*/isEqualOp);
7879 }
7880 }
7881 }
7882
7883 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7884 for (BuiltinCandidateTypeSet::iterator
7885 Vec1 = CandidateTypes[0].vector_begin(),
7886 Vec1End = CandidateTypes[0].vector_end();
7887 Vec1 != Vec1End; ++Vec1) {
7888 for (BuiltinCandidateTypeSet::iterator
7889 Vec2 = CandidateTypes[1].vector_begin(),
7890 Vec2End = CandidateTypes[1].vector_end();
7891 Vec2 != Vec2End; ++Vec2) {
7892 QualType ParamTypes[2];
7893 ParamTypes[1] = *Vec2;
7894 // Add this built-in operator as a candidate (VQ is empty).
7895 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007896 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007897 /*IsAssigmentOperator=*/isEqualOp);
7898
7899 // Add this built-in operator as a candidate (VQ is 'volatile').
7900 if (VisibleTypeConversionsQuals.hasVolatile()) {
7901 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7902 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007903 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007904 /*IsAssigmentOperator=*/isEqualOp);
7905 }
7906 }
7907 }
7908 }
7909
7910 // C++ [over.built]p22:
7911 //
7912 // For every triple (L, VQ, R), where L is an integral type, VQ
7913 // is either volatile or empty, and R is a promoted integral
7914 // type, there exist candidate operator functions of the form
7915 //
7916 // VQ L& operator%=(VQ L&, R);
7917 // VQ L& operator<<=(VQ L&, R);
7918 // VQ L& operator>>=(VQ L&, R);
7919 // VQ L& operator&=(VQ L&, R);
7920 // VQ L& operator^=(VQ L&, R);
7921 // VQ L& operator|=(VQ L&, R);
7922 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007923 if (!HasArithmeticOrEnumeralCandidateType)
7924 return;
7925
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007926 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7927 for (unsigned Right = FirstPromotedIntegralType;
7928 Right < LastPromotedIntegralType; ++Right) {
7929 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007930 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007931
7932 // Add this built-in operator as a candidate (VQ is empty).
7933 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007934 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007935 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007936 if (VisibleTypeConversionsQuals.hasVolatile()) {
7937 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007938 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007939 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7940 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007941 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007942 }
7943 }
7944 }
7945 }
7946
7947 // C++ [over.operator]p23:
7948 //
7949 // There also exist candidate operator functions of the form
7950 //
7951 // bool operator!(bool);
7952 // bool operator&&(bool, bool);
7953 // bool operator||(bool, bool);
7954 void addExclaimOverload() {
7955 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007956 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007957 /*IsAssignmentOperator=*/false,
7958 /*NumContextualBoolArguments=*/1);
7959 }
7960 void addAmpAmpOrPipePipeOverload() {
7961 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007962 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007963 /*IsAssignmentOperator=*/false,
7964 /*NumContextualBoolArguments=*/2);
7965 }
7966
7967 // C++ [over.built]p13:
7968 //
7969 // For every cv-qualified or cv-unqualified object type T there
7970 // exist candidate operator functions of the form
7971 //
7972 // T* operator+(T*, ptrdiff_t); [ABOVE]
7973 // T& operator[](T*, ptrdiff_t);
7974 // T* operator-(T*, ptrdiff_t); [ABOVE]
7975 // T* operator+(ptrdiff_t, T*); [ABOVE]
7976 // T& operator[](ptrdiff_t, T*);
7977 void addSubscriptOverloads() {
7978 for (BuiltinCandidateTypeSet::iterator
7979 Ptr = CandidateTypes[0].pointer_begin(),
7980 PtrEnd = CandidateTypes[0].pointer_end();
7981 Ptr != PtrEnd; ++Ptr) {
7982 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7983 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007984 if (!PointeeType->isObjectType())
7985 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007986
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007987 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7988
7989 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007990 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007991 }
7992
7993 for (BuiltinCandidateTypeSet::iterator
7994 Ptr = CandidateTypes[1].pointer_begin(),
7995 PtrEnd = CandidateTypes[1].pointer_end();
7996 Ptr != PtrEnd; ++Ptr) {
7997 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7998 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007999 if (!PointeeType->isObjectType())
8000 continue;
8001
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008002 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8003
8004 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008005 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008006 }
8007 }
8008
8009 // C++ [over.built]p11:
8010 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8011 // C1 is the same type as C2 or is a derived class of C2, T is an object
8012 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8013 // there exist candidate operator functions of the form
8014 //
8015 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8016 //
8017 // where CV12 is the union of CV1 and CV2.
8018 void addArrowStarOverloads() {
8019 for (BuiltinCandidateTypeSet::iterator
8020 Ptr = CandidateTypes[0].pointer_begin(),
8021 PtrEnd = CandidateTypes[0].pointer_end();
8022 Ptr != PtrEnd; ++Ptr) {
8023 QualType C1Ty = (*Ptr);
8024 QualType C1;
8025 QualifierCollector Q1;
8026 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8027 if (!isa<RecordType>(C1))
8028 continue;
8029 // heuristic to reduce number of builtin candidates in the set.
8030 // Add volatile/restrict version only if there are conversions to a
8031 // volatile/restrict type.
8032 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8033 continue;
8034 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8035 continue;
8036 for (BuiltinCandidateTypeSet::iterator
8037 MemPtr = CandidateTypes[1].member_pointer_begin(),
8038 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8039 MemPtr != MemPtrEnd; ++MemPtr) {
8040 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8041 QualType C2 = QualType(mptr->getClass(), 0);
8042 C2 = C2.getUnqualifiedType();
8043 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8044 break;
8045 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8046 // build CV12 T&
8047 QualType T = mptr->getPointeeType();
8048 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8049 T.isVolatileQualified())
8050 continue;
8051 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8052 T.isRestrictQualified())
8053 continue;
8054 T = Q1.apply(S.Context, T);
8055 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008056 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008057 }
8058 }
8059 }
8060
8061 // Note that we don't consider the first argument, since it has been
8062 // contextually converted to bool long ago. The candidates below are
8063 // therefore added as binary.
8064 //
8065 // C++ [over.built]p25:
8066 // For every type T, where T is a pointer, pointer-to-member, or scoped
8067 // enumeration type, there exist candidate operator functions of the form
8068 //
8069 // T operator?(bool, T, T);
8070 //
8071 void addConditionalOperatorOverloads() {
8072 /// Set of (canonical) types that we've already handled.
8073 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8074
8075 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8076 for (BuiltinCandidateTypeSet::iterator
8077 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8078 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8079 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008080 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008081 continue;
8082
8083 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008084 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008085 }
8086
8087 for (BuiltinCandidateTypeSet::iterator
8088 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8089 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8090 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008091 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008092 continue;
8093
8094 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008095 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008096 }
8097
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008098 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008099 for (BuiltinCandidateTypeSet::iterator
8100 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8101 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8102 Enum != EnumEnd; ++Enum) {
8103 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8104 continue;
8105
David Blaikie82e95a32014-11-19 07:49:47 +00008106 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008107 continue;
8108
8109 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008110 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008111 }
8112 }
8113 }
8114 }
8115};
8116
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008117} // end anonymous namespace
8118
8119/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8120/// operator overloads to the candidate set (C++ [over.built]), based
8121/// on the operator @p Op and the arguments given. For example, if the
8122/// operator is a binary '+', this routine might add "int
8123/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008124void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8125 SourceLocation OpLoc,
8126 ArrayRef<Expr *> Args,
8127 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008128 // Find all of the types that the arguments can convert to, but only
8129 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008130 // that make use of these types. Also record whether we encounter non-record
8131 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008132 Qualifiers VisibleTypeConversionsQuals;
8133 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008134 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008135 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008136
8137 bool HasNonRecordCandidateType = false;
8138 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008139 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008140 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008141 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
8142 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8143 OpLoc,
8144 true,
8145 (Op == OO_Exclaim ||
8146 Op == OO_AmpAmp ||
8147 Op == OO_PipePipe),
8148 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008149 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8150 CandidateTypes[ArgIdx].hasNonRecordTypes();
8151 HasArithmeticOrEnumeralCandidateType =
8152 HasArithmeticOrEnumeralCandidateType ||
8153 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008154 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008155
Chandler Carruth00a38332010-12-13 01:44:01 +00008156 // Exit early when no non-record types have been added to the candidate set
8157 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008158 //
8159 // We can't exit early for !, ||, or &&, since there we have always have
8160 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008161 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008162 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008163 return;
8164
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008165 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008166 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008167 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008168 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008169 CandidateTypes, CandidateSet);
8170
8171 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008172 switch (Op) {
8173 case OO_None:
8174 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008175 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008176
Chandler Carruth5184de02010-12-12 08:51:33 +00008177 case OO_New:
8178 case OO_Delete:
8179 case OO_Array_New:
8180 case OO_Array_Delete:
8181 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008182 llvm_unreachable(
8183 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008184
8185 case OO_Comma:
8186 case OO_Arrow:
8187 // C++ [over.match.oper]p3:
8188 // -- For the operator ',', the unary operator '&', or the
8189 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008190 break;
8191
8192 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008193 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008194 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008195 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008196
8197 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008198 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008199 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008200 } else {
8201 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8202 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8203 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008204 break;
8205
Chandler Carruth5184de02010-12-12 08:51:33 +00008206 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008207 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008208 OpBuilder.addUnaryStarPointerOverloads();
8209 else
8210 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8211 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008212
Chandler Carruth5184de02010-12-12 08:51:33 +00008213 case OO_Slash:
8214 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008215 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008216
8217 case OO_PlusPlus:
8218 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008219 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8220 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008221 break;
8222
Douglas Gregor84605ae2009-08-24 13:43:27 +00008223 case OO_EqualEqual:
8224 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008225 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008226 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008227
Douglas Gregora11693b2008-11-12 17:17:38 +00008228 case OO_Less:
8229 case OO_Greater:
8230 case OO_LessEqual:
8231 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008232 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008233 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8234 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008235
Douglas Gregora11693b2008-11-12 17:17:38 +00008236 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008237 case OO_Caret:
8238 case OO_Pipe:
8239 case OO_LessLess:
8240 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008241 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008242 break;
8243
Chandler Carruth5184de02010-12-12 08:51:33 +00008244 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008245 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008246 // C++ [over.match.oper]p3:
8247 // -- For the operator ',', the unary operator '&', or the
8248 // operator '->', the built-in candidates set is empty.
8249 break;
8250
8251 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8252 break;
8253
8254 case OO_Tilde:
8255 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8256 break;
8257
Douglas Gregora11693b2008-11-12 17:17:38 +00008258 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008259 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008260 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008261
8262 case OO_PlusEqual:
8263 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008264 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008265 // Fall through.
8266
8267 case OO_StarEqual:
8268 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008269 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008270 break;
8271
8272 case OO_PercentEqual:
8273 case OO_LessLessEqual:
8274 case OO_GreaterGreaterEqual:
8275 case OO_AmpEqual:
8276 case OO_CaretEqual:
8277 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008278 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008279 break;
8280
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008281 case OO_Exclaim:
8282 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008283 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008284
Douglas Gregora11693b2008-11-12 17:17:38 +00008285 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008286 case OO_PipePipe:
8287 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008288 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008289
8290 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008291 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008292 break;
8293
8294 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008295 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008296 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008297
8298 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008299 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008300 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8301 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008302 }
8303}
8304
Douglas Gregore254f902009-02-04 00:32:51 +00008305/// \brief Add function candidates found via argument-dependent lookup
8306/// to the set of overloading candidates.
8307///
8308/// This routine performs argument-dependent name lookup based on the
8309/// given function name (which may also be an operator name) and adds
8310/// all of the overload candidates found by ADL to the overload
8311/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008312void
Douglas Gregore254f902009-02-04 00:32:51 +00008313Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008314 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008315 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008316 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008317 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008318 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008319 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008320
John McCall91f61fc2010-01-26 06:04:06 +00008321 // FIXME: This approach for uniquing ADL results (and removing
8322 // redundant candidates from the set) relies on pointer-equality,
8323 // which means we need to key off the canonical decl. However,
8324 // always going back to the canonical decl might not get us the
8325 // right set of default arguments. What default arguments are
8326 // we supposed to consider on ADL candidates, anyway?
8327
Douglas Gregorcabea402009-09-22 15:41:20 +00008328 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008329 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008330
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008331 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008332 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8333 CandEnd = CandidateSet.end();
8334 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008335 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008336 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008337 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008338 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008339 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008340
8341 // For each of the ADL candidates we found, add it to the overload
8342 // set.
John McCall8fe68082010-01-26 07:16:45 +00008343 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008344 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008345 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008346 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008347 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008348
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008349 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8350 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008351 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008352 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008353 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008354 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008355 }
Douglas Gregore254f902009-02-04 00:32:51 +00008356}
8357
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008358/// isBetterOverloadCandidate - Determines whether the first overload
8359/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008360bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8361 const OverloadCandidate &Cand2,
8362 SourceLocation Loc,
8363 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008364 // Define viable functions to be better candidates than non-viable
8365 // functions.
8366 if (!Cand2.Viable)
8367 return Cand1.Viable;
8368 else if (!Cand1.Viable)
8369 return false;
8370
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008371 // C++ [over.match.best]p1:
8372 //
8373 // -- if F is a static member function, ICS1(F) is defined such
8374 // that ICS1(F) is neither better nor worse than ICS1(G) for
8375 // any function G, and, symmetrically, ICS1(G) is neither
8376 // better nor worse than ICS1(F).
8377 unsigned StartArg = 0;
8378 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8379 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008380
Douglas Gregord3cb3562009-07-07 23:38:56 +00008381 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008382 // A viable function F1 is defined to be a better function than another
8383 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008384 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008385 unsigned NumArgs = Cand1.NumConversions;
8386 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008387 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008388 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008389 switch (CompareImplicitConversionSequences(S,
8390 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008391 Cand2.Conversions[ArgIdx])) {
8392 case ImplicitConversionSequence::Better:
8393 // Cand1 has a better conversion sequence.
8394 HasBetterConversion = true;
8395 break;
8396
8397 case ImplicitConversionSequence::Worse:
8398 // Cand1 can't be better than Cand2.
8399 return false;
8400
8401 case ImplicitConversionSequence::Indistinguishable:
8402 // Do nothing.
8403 break;
8404 }
8405 }
8406
Mike Stump11289f42009-09-09 15:08:12 +00008407 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008408 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008409 if (HasBetterConversion)
8410 return true;
8411
Douglas Gregora1f013e2008-11-07 22:36:19 +00008412 // -- the context is an initialization by user-defined conversion
8413 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8414 // from the return type of F1 to the destination type (i.e.,
8415 // the type of the entity being initialized) is a better
8416 // conversion sequence than the standard conversion sequence
8417 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008418 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008419 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008420 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008421 // First check whether we prefer one of the conversion functions over the
8422 // other. This only distinguishes the results in non-standard, extension
8423 // cases such as the conversion from a lambda closure type to a function
8424 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008425 ImplicitConversionSequence::CompareKind Result =
8426 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8427 if (Result == ImplicitConversionSequence::Indistinguishable)
8428 Result = CompareStandardConversionSequences(S,
8429 Cand1.FinalConversion,
8430 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008431
Richard Smithec2748a2014-05-17 04:36:39 +00008432 if (Result != ImplicitConversionSequence::Indistinguishable)
8433 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008434
8435 // FIXME: Compare kind of reference binding if conversion functions
8436 // convert to a reference type used in direct reference binding, per
8437 // C++14 [over.match.best]p1 section 2 bullet 3.
8438 }
8439
8440 // -- F1 is a non-template function and F2 is a function template
8441 // specialization, or, if not that,
8442 bool Cand1IsSpecialization = Cand1.Function &&
8443 Cand1.Function->getPrimaryTemplate();
8444 bool Cand2IsSpecialization = Cand2.Function &&
8445 Cand2.Function->getPrimaryTemplate();
8446 if (Cand1IsSpecialization != Cand2IsSpecialization)
8447 return Cand2IsSpecialization;
8448
8449 // -- F1 and F2 are function template specializations, and the function
8450 // template for F1 is more specialized than the template for F2
8451 // according to the partial ordering rules described in 14.5.5.2, or,
8452 // if not that,
8453 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8454 if (FunctionTemplateDecl *BetterTemplate
8455 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8456 Cand2.Function->getPrimaryTemplate(),
8457 Loc,
8458 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8459 : TPOC_Call,
8460 Cand1.ExplicitCallArguments,
8461 Cand2.ExplicitCallArguments))
8462 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008463 }
8464
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008465 // Check for enable_if value-based overload resolution.
8466 if (Cand1.Function && Cand2.Function &&
8467 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8468 Cand2.Function->hasAttr<EnableIfAttr>())) {
8469 // FIXME: The next several lines are just
8470 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8471 // instead of reverse order which is how they're stored in the AST.
8472 AttrVec Cand1Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008473 if (Cand1.Function->hasAttrs()) {
8474 Cand1Attrs = Cand1.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008475 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8476 IsNotEnableIfAttr),
8477 Cand1Attrs.end());
8478 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008479 }
8480
8481 AttrVec Cand2Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008482 if (Cand2.Function->hasAttrs()) {
8483 Cand2Attrs = Cand2.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008484 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8485 IsNotEnableIfAttr),
8486 Cand2Attrs.end());
8487 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008488 }
Richard Smith9516eee2014-05-17 02:21:47 +00008489
8490 // Candidate 1 is better if it has strictly more attributes and
8491 // the common sequence is identical.
8492 if (Cand1Attrs.size() <= Cand2Attrs.size())
8493 return false;
8494
8495 auto Cand1I = Cand1Attrs.begin();
8496 for (auto &Cand2A : Cand2Attrs) {
8497 auto &Cand1A = *Cand1I++;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008498 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Richard Smith9516eee2014-05-17 02:21:47 +00008499 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8500 S.getASTContext(), true);
8501 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8502 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008503 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008504 return false;
8505 }
Richard Smith9516eee2014-05-17 02:21:47 +00008506
8507 return true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008508 }
8509
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008510 return false;
8511}
8512
Mike Stump11289f42009-09-09 15:08:12 +00008513/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008514/// within an overload candidate set.
8515///
James Dennettffad8b72012-06-22 08:10:18 +00008516/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008517/// which overload resolution occurs.
8518///
James Dennettffad8b72012-06-22 08:10:18 +00008519/// \param Best If overload resolution was successful or found a deleted
8520/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008521///
8522/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008523OverloadingResult
8524OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008525 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008526 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008527 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008528 Best = end();
8529 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8530 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008531 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008532 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008533 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008534 }
8535
8536 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008537 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008538 return OR_No_Viable_Function;
8539
8540 // Make sure that this function is better than every other viable
8541 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008542 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008543 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008544 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008545 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008546 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008547 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008548 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008549 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008550 }
Mike Stump11289f42009-09-09 15:08:12 +00008551
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008552 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008553 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008554 (Best->Function->isDeleted() ||
8555 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008556 return OR_Deleted;
8557
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008558 return OR_Success;
8559}
8560
John McCall53262c92010-01-12 02:15:36 +00008561namespace {
8562
8563enum OverloadCandidateKind {
8564 oc_function,
8565 oc_method,
8566 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008567 oc_function_template,
8568 oc_method_template,
8569 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008570 oc_implicit_default_constructor,
8571 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008572 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008573 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008574 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008575 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008576};
8577
John McCalle1ac8d12010-01-13 00:25:19 +00008578OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8579 FunctionDecl *Fn,
8580 std::string &Description) {
8581 bool isTemplate = false;
8582
8583 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8584 isTemplate = true;
8585 Description = S.getTemplateArgumentBindingsText(
8586 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8587 }
John McCallfd0b2f82010-01-06 09:43:14 +00008588
8589 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008590 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008591 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008592
Sebastian Redl08905022011-02-05 19:23:19 +00008593 if (Ctor->getInheritedConstructor())
8594 return oc_implicit_inherited_constructor;
8595
Alexis Hunt119c10e2011-05-25 23:16:36 +00008596 if (Ctor->isDefaultConstructor())
8597 return oc_implicit_default_constructor;
8598
8599 if (Ctor->isMoveConstructor())
8600 return oc_implicit_move_constructor;
8601
8602 assert(Ctor->isCopyConstructor() &&
8603 "unexpected sort of implicit constructor");
8604 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008605 }
8606
8607 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8608 // This actually gets spelled 'candidate function' for now, but
8609 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008610 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008611 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008612
Alexis Hunt119c10e2011-05-25 23:16:36 +00008613 if (Meth->isMoveAssignmentOperator())
8614 return oc_implicit_move_assignment;
8615
Douglas Gregor12695102012-02-10 08:36:38 +00008616 if (Meth->isCopyAssignmentOperator())
8617 return oc_implicit_copy_assignment;
8618
8619 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8620 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008621 }
8622
John McCalle1ac8d12010-01-13 00:25:19 +00008623 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008624}
8625
Larisse Voufo98b20f12013-07-19 23:00:19 +00008626void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008627 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8628 if (!Ctor) return;
8629
8630 Ctor = Ctor->getInheritedConstructor();
8631 if (!Ctor) return;
8632
8633 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8634}
8635
John McCall53262c92010-01-12 02:15:36 +00008636} // end anonymous namespace
8637
8638// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008639void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008640 std::string FnDesc;
8641 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008642 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8643 << (unsigned) K << FnDesc;
8644 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8645 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008646 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008647}
8648
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008649// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008650// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008651void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008652 assert(OverloadedExpr->getType() == Context.OverloadTy);
8653
8654 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8655 OverloadExpr *OvlExpr = Ovl.Expression;
8656
8657 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8658 IEnd = OvlExpr->decls_end();
8659 I != IEnd; ++I) {
8660 if (FunctionTemplateDecl *FunTmpl =
8661 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008662 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008663 } else if (FunctionDecl *Fun
8664 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008665 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008666 }
8667 }
8668}
8669
John McCall0d1da222010-01-12 00:44:57 +00008670/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8671/// "lead" diagnostic; it will be given two arguments, the source and
8672/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008673void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8674 Sema &S,
8675 SourceLocation CaretLoc,
8676 const PartialDiagnostic &PDiag) const {
8677 S.Diag(CaretLoc, PDiag)
8678 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008679 // FIXME: The note limiting machinery is borrowed from
8680 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8681 // refactoring here.
8682 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8683 unsigned CandsShown = 0;
8684 AmbiguousConversionSequence::const_iterator I, E;
8685 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8686 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8687 break;
8688 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008689 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008690 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008691 if (I != E)
8692 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008693}
8694
Richard Smith17c00b42014-11-12 01:24:00 +00008695static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8696 unsigned I) {
John McCall6a61b522010-01-13 09:16:55 +00008697 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8698 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008699 assert(Cand->Function && "for now, candidate must be a function");
8700 FunctionDecl *Fn = Cand->Function;
8701
8702 // There's a conversion slot for the object argument if this is a
8703 // non-constructor method. Note that 'I' corresponds the
8704 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008705 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008706 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008707 if (I == 0)
8708 isObjectArgument = true;
8709 else
8710 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008711 }
8712
John McCalle1ac8d12010-01-13 00:25:19 +00008713 std::string FnDesc;
8714 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8715
John McCall6a61b522010-01-13 09:16:55 +00008716 Expr *FromExpr = Conv.Bad.FromExpr;
8717 QualType FromTy = Conv.Bad.getFromType();
8718 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008719
John McCallfb7ad0f2010-02-02 02:42:52 +00008720 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008721 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008722 Expr *E = FromExpr->IgnoreParens();
8723 if (isa<UnaryOperator>(E))
8724 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008725 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008726
8727 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8728 << (unsigned) FnKind << FnDesc
8729 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8730 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008731 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008732 return;
8733 }
8734
John McCall6d174642010-01-23 08:10:49 +00008735 // Do some hand-waving analysis to see if the non-viability is due
8736 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008737 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8738 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8739 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8740 CToTy = RT->getPointeeType();
8741 else {
8742 // TODO: detect and diagnose the full richness of const mismatches.
8743 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8744 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8745 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8746 }
8747
8748 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8749 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008750 Qualifiers FromQs = CFromTy.getQualifiers();
8751 Qualifiers ToQs = CToTy.getQualifiers();
8752
8753 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8754 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8755 << (unsigned) FnKind << FnDesc
8756 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8757 << FromTy
8758 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8759 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008760 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008761 return;
8762 }
8763
John McCall31168b02011-06-15 23:02:42 +00008764 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008765 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008766 << (unsigned) FnKind << FnDesc
8767 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8768 << FromTy
8769 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8770 << (unsigned) isObjectArgument << I+1;
8771 MaybeEmitInheritedConstructorNote(S, Fn);
8772 return;
8773 }
8774
Douglas Gregoraec25842011-04-26 23:16:46 +00008775 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8776 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8777 << (unsigned) FnKind << FnDesc
8778 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8779 << FromTy
8780 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8781 << (unsigned) isObjectArgument << I+1;
8782 MaybeEmitInheritedConstructorNote(S, Fn);
8783 return;
8784 }
8785
John McCall47000992010-01-14 03:28:57 +00008786 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8787 assert(CVR && "unexpected qualifiers mismatch");
8788
8789 if (isObjectArgument) {
8790 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8791 << (unsigned) FnKind << FnDesc
8792 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8793 << FromTy << (CVR - 1);
8794 } else {
8795 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8796 << (unsigned) FnKind << FnDesc
8797 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8798 << FromTy << (CVR - 1) << I+1;
8799 }
Sebastian Redl08905022011-02-05 19:23:19 +00008800 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008801 return;
8802 }
8803
Sebastian Redla72462c2011-09-24 17:48:32 +00008804 // Special diagnostic for failure to convert an initializer list, since
8805 // telling the user that it has type void is not useful.
8806 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8807 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8808 << (unsigned) FnKind << FnDesc
8809 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8810 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8811 MaybeEmitInheritedConstructorNote(S, Fn);
8812 return;
8813 }
8814
John McCall6d174642010-01-23 08:10:49 +00008815 // Diagnose references or pointers to incomplete types differently,
8816 // since it's far from impossible that the incompleteness triggered
8817 // the failure.
8818 QualType TempFromTy = FromTy.getNonReferenceType();
8819 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8820 TempFromTy = PTy->getPointeeType();
8821 if (TempFromTy->isIncompleteType()) {
8822 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8823 << (unsigned) FnKind << FnDesc
8824 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8825 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008826 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008827 return;
8828 }
8829
Douglas Gregor56f2e342010-06-30 23:01:39 +00008830 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008831 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008832 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8833 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8834 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8835 FromPtrTy->getPointeeType()) &&
8836 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8837 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008838 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008839 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008840 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008841 }
8842 } else if (const ObjCObjectPointerType *FromPtrTy
8843 = FromTy->getAs<ObjCObjectPointerType>()) {
8844 if (const ObjCObjectPointerType *ToPtrTy
8845 = ToTy->getAs<ObjCObjectPointerType>())
8846 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8847 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8848 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8849 FromPtrTy->getPointeeType()) &&
8850 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008851 BaseToDerivedConversion = 2;
8852 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008853 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8854 !FromTy->isIncompleteType() &&
8855 !ToRefTy->getPointeeType()->isIncompleteType() &&
8856 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8857 BaseToDerivedConversion = 3;
8858 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8859 ToTy.getNonReferenceType().getCanonicalType() ==
8860 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008861 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8862 << (unsigned) FnKind << FnDesc
8863 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8864 << (unsigned) isObjectArgument << I + 1;
8865 MaybeEmitInheritedConstructorNote(S, Fn);
8866 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008867 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008868 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008869
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008870 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008871 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008872 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008873 << (unsigned) FnKind << FnDesc
8874 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008875 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008876 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008877 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008878 return;
8879 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008880
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008881 if (isa<ObjCObjectPointerType>(CFromTy) &&
8882 isa<PointerType>(CToTy)) {
8883 Qualifiers FromQs = CFromTy.getQualifiers();
8884 Qualifiers ToQs = CToTy.getQualifiers();
8885 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8886 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8887 << (unsigned) FnKind << FnDesc
8888 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8889 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8890 MaybeEmitInheritedConstructorNote(S, Fn);
8891 return;
8892 }
8893 }
8894
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008895 // Emit the generic diagnostic and, optionally, add the hints to it.
8896 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8897 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008898 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008899 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8900 << (unsigned) (Cand->Fix.Kind);
8901
8902 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008903 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8904 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008905 FDiag << *HI;
8906 S.Diag(Fn->getLocation(), FDiag);
8907
Sebastian Redl08905022011-02-05 19:23:19 +00008908 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008909}
8910
Larisse Voufo98b20f12013-07-19 23:00:19 +00008911/// Additional arity mismatch diagnosis specific to a function overload
8912/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8913/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008914static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8915 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008916 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008917 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008918
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008919 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008920 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008921 // right number of arguments, because only overloaded operators have
8922 // the weird behavior of overloading member and non-member functions.
8923 // Just don't report anything.
8924 if (Fn->isInvalidDecl() &&
8925 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008926 return true;
8927
8928 if (NumArgs < MinParams) {
8929 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8930 (Cand->FailureKind == ovl_fail_bad_deduction &&
8931 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8932 } else {
8933 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8934 (Cand->FailureKind == ovl_fail_bad_deduction &&
8935 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8936 }
8937
8938 return false;
8939}
8940
8941/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008942static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008943 assert(isa<FunctionDecl>(D) &&
8944 "The templated declaration should at least be a function"
8945 " when diagnosing bad template argument deduction due to too many"
8946 " or too few arguments");
8947
8948 FunctionDecl *Fn = cast<FunctionDecl>(D);
8949
8950 // TODO: treat calls to a missing default constructor as a special case
8951 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8952 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008953
John McCall6a61b522010-01-13 09:16:55 +00008954 // at least / at most / exactly
8955 unsigned mode, modeCount;
8956 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008957 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8958 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008959 mode = 0; // "at least"
8960 else
8961 mode = 2; // "exactly"
8962 modeCount = MinParams;
8963 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008964 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008965 mode = 1; // "at most"
8966 else
8967 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008968 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008969 }
8970
8971 std::string Description;
8972 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8973
Richard Smith10ff50d2012-05-11 05:16:41 +00008974 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8975 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00008976 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8977 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00008978 else
8979 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00008980 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8981 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008982 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008983}
8984
Larisse Voufo98b20f12013-07-19 23:00:19 +00008985/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00008986static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8987 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008988 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8989 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8990}
Larisse Voufo47c08452013-07-19 22:53:23 +00008991
Richard Smith17c00b42014-11-12 01:24:00 +00008992static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008993 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8994 return FD->getDescribedFunctionTemplate();
8995 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8996 return RD->getDescribedClassTemplate();
8997
8998 llvm_unreachable("Unsupported: Getting the described template declaration"
8999 " for bad deduction diagnosis");
9000}
9001
9002/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00009003static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9004 DeductionFailureInfo &DeductionFailure,
9005 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009006 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009007 NamedDecl *ParamD;
9008 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9009 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9010 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009011 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009012 case Sema::TDK_Success:
9013 llvm_unreachable("TDK_success while diagnosing bad deduction");
9014
9015 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009016 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009017 S.Diag(Templated->getLocation(),
9018 diag::note_ovl_candidate_incomplete_deduction)
9019 << ParamD->getDeclName();
9020 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009021 return;
9022 }
9023
John McCall42d7d192010-08-05 09:05:08 +00009024 case Sema::TDK_Underqualified: {
9025 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9026 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9027
Larisse Voufo98b20f12013-07-19 23:00:19 +00009028 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009029
9030 // Param will have been canonicalized, but it should just be a
9031 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009032 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009033 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009034 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009035 assert(S.Context.hasSameType(Param, NonCanonParam));
9036
9037 // Arg has also been canonicalized, but there's nothing we can do
9038 // about that. It also doesn't matter as much, because it won't
9039 // have any template parameters in it (because deduction isn't
9040 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009041 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009042
Larisse Voufo98b20f12013-07-19 23:00:19 +00009043 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9044 << ParamD->getDeclName() << Arg << NonCanonParam;
9045 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009046 return;
9047 }
9048
9049 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009050 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009051 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009052 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009053 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009054 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009055 which = 1;
9056 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009057 which = 2;
9058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009059
Larisse Voufo98b20f12013-07-19 23:00:19 +00009060 S.Diag(Templated->getLocation(),
9061 diag::note_ovl_candidate_inconsistent_deduction)
9062 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9063 << *DeductionFailure.getSecondArg();
9064 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009065 return;
9066 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009067
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009068 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009069 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009070 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009071 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009072 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009073 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009074 else {
9075 int index = 0;
9076 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9077 index = TTP->getIndex();
9078 else if (NonTypeTemplateParmDecl *NTTP
9079 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9080 index = NTTP->getIndex();
9081 else
9082 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009083 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009084 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009085 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009086 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009087 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009088 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009089
Douglas Gregor02eb4832010-05-08 18:13:28 +00009090 case Sema::TDK_TooManyArguments:
9091 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009092 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009093 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009094
9095 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009096 S.Diag(Templated->getLocation(),
9097 diag::note_ovl_candidate_instantiation_depth);
9098 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009099 return;
9100
9101 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009102 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009103 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009104 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009105 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009106 TemplateArgString = " ";
9107 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009108 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009109 }
9110
Richard Smith6f8d2c62012-05-09 05:17:00 +00009111 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009112 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009113 if (PDiag && PDiag->second.getDiagID() ==
9114 diag::err_typename_nested_not_found_enable_if) {
9115 // FIXME: Use the source range of the condition, and the fully-qualified
9116 // name of the enable_if template. These are both present in PDiag.
9117 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9118 << "'enable_if'" << TemplateArgString;
9119 return;
9120 }
9121
Richard Smith9ca64612012-05-07 09:03:25 +00009122 // Format the SFINAE diagnostic into the argument string.
9123 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9124 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009125 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009126 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009127 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009128 SFINAEArgString = ": ";
9129 R = SourceRange(PDiag->first, PDiag->first);
9130 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9131 }
9132
Larisse Voufo98b20f12013-07-19 23:00:19 +00009133 S.Diag(Templated->getLocation(),
9134 diag::note_ovl_candidate_substitution_failure)
9135 << TemplateArgString << SFINAEArgString << R;
9136 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009137 return;
9138 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009139
Richard Smith8c6eeb92013-01-31 04:03:12 +00009140 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009141 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9142 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009143 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009144 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009145 return;
9146 }
9147
Richard Trieue3732352013-04-08 21:11:40 +00009148 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009149 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009150 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9151 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009152 if (FirstTA.getKind() == TemplateArgument::Template &&
9153 SecondTA.getKind() == TemplateArgument::Template) {
9154 TemplateName FirstTN = FirstTA.getAsTemplate();
9155 TemplateName SecondTN = SecondTA.getAsTemplate();
9156 if (FirstTN.getKind() == TemplateName::Template &&
9157 SecondTN.getKind() == TemplateName::Template) {
9158 if (FirstTN.getAsTemplateDecl()->getName() ==
9159 SecondTN.getAsTemplateDecl()->getName()) {
9160 // FIXME: This fixes a bad diagnostic where both templates are named
9161 // the same. This particular case is a bit difficult since:
9162 // 1) It is passed as a string to the diagnostic printer.
9163 // 2) The diagnostic printer only attempts to find a better
9164 // name for types, not decls.
9165 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009166 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009167 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9168 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9169 return;
9170 }
9171 }
9172 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00009173 // FIXME: For generic lambda parameters, check if the function is a lambda
9174 // call operator, and if so, emit a prettier and more informative
9175 // diagnostic that mentions 'auto' and lambda in addition to
9176 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009177 S.Diag(Templated->getLocation(),
9178 diag::note_ovl_candidate_non_deduced_mismatch)
9179 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009180 return;
Richard Trieue3732352013-04-08 21:11:40 +00009181 }
John McCall8b9ed552010-02-01 18:53:26 +00009182 // TODO: diagnose these individually, then kill off
9183 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009184 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009185 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9186 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009187 return;
9188 }
9189}
9190
Larisse Voufo98b20f12013-07-19 23:00:19 +00009191/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009192static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9193 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009194 unsigned TDK = Cand->DeductionFailure.Result;
9195 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9196 if (CheckArityMismatch(S, Cand, NumArgs))
9197 return;
9198 }
9199 DiagnoseBadDeduction(S, Cand->Function, // pattern
9200 Cand->DeductionFailure, NumArgs);
9201}
9202
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009203/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009204static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009205 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9206 FunctionDecl *Callee = Cand->Function;
9207
9208 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9209 CalleeTarget = S.IdentifyCUDATarget(Callee);
9210
9211 std::string FnDesc;
9212 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9213
9214 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009215 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9216
9217 // This could be an implicit constructor for which we could not infer the
9218 // target due to a collsion. Diagnose that case.
9219 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9220 if (Meth != nullptr && Meth->isImplicit()) {
9221 CXXRecordDecl *ParentClass = Meth->getParent();
9222 Sema::CXXSpecialMember CSM;
9223
9224 switch (FnKind) {
9225 default:
9226 return;
9227 case oc_implicit_default_constructor:
9228 CSM = Sema::CXXDefaultConstructor;
9229 break;
9230 case oc_implicit_copy_constructor:
9231 CSM = Sema::CXXCopyConstructor;
9232 break;
9233 case oc_implicit_move_constructor:
9234 CSM = Sema::CXXMoveConstructor;
9235 break;
9236 case oc_implicit_copy_assignment:
9237 CSM = Sema::CXXCopyAssignment;
9238 break;
9239 case oc_implicit_move_assignment:
9240 CSM = Sema::CXXMoveAssignment;
9241 break;
9242 };
9243
9244 bool ConstRHS = false;
9245 if (Meth->getNumParams()) {
9246 if (const ReferenceType *RT =
9247 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9248 ConstRHS = RT->getPointeeType().isConstQualified();
9249 }
9250 }
9251
9252 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9253 /* ConstRHS */ ConstRHS,
9254 /* Diagnose */ true);
9255 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009256}
9257
Richard Smith17c00b42014-11-12 01:24:00 +00009258static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009259 FunctionDecl *Callee = Cand->Function;
9260 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9261
9262 S.Diag(Callee->getLocation(),
9263 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9264 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9265}
9266
John McCall8b9ed552010-02-01 18:53:26 +00009267/// Generates a 'note' diagnostic for an overload candidate. We've
9268/// already generated a primary error at the call site.
9269///
9270/// It really does need to be a single diagnostic with its caret
9271/// pointed at the candidate declaration. Yes, this creates some
9272/// major challenges of technical writing. Yes, this makes pointing
9273/// out problems with specific arguments quite awkward. It's still
9274/// better than generating twenty screens of text for every failed
9275/// overload.
9276///
9277/// It would be great to be able to express per-candidate problems
9278/// more richly for those diagnostic clients that cared, but we'd
9279/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009280static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9281 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009282 FunctionDecl *Fn = Cand->Function;
9283
John McCall12f97bc2010-01-08 04:41:39 +00009284 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009285 if (Cand->Viable && (Fn->isDeleted() ||
9286 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009287 std::string FnDesc;
9288 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009289
9290 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009291 << FnKind << FnDesc
9292 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009293 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009294 return;
John McCall12f97bc2010-01-08 04:41:39 +00009295 }
9296
John McCalle1ac8d12010-01-13 00:25:19 +00009297 // We don't really have anything else to say about viable candidates.
9298 if (Cand->Viable) {
9299 S.NoteOverloadCandidate(Fn);
9300 return;
9301 }
John McCall0d1da222010-01-12 00:44:57 +00009302
John McCall6a61b522010-01-13 09:16:55 +00009303 switch (Cand->FailureKind) {
9304 case ovl_fail_too_many_arguments:
9305 case ovl_fail_too_few_arguments:
9306 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009307
John McCall6a61b522010-01-13 09:16:55 +00009308 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009309 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009310
John McCall578a1f82014-12-14 01:46:53 +00009311 case ovl_fail_illegal_constructor: {
9312 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9313 << (Fn->getPrimaryTemplate() ? 1 : 0);
9314 MaybeEmitInheritedConstructorNote(S, Fn);
9315 return;
9316 }
9317
John McCallfe796dd2010-01-23 05:17:32 +00009318 case ovl_fail_trivial_conversion:
9319 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009320 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009321 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009322
John McCall65eb8792010-02-25 01:37:24 +00009323 case ovl_fail_bad_conversion: {
9324 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009325 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009326 if (Cand->Conversions[I].isBad())
9327 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009328
John McCall6a61b522010-01-13 09:16:55 +00009329 // FIXME: this currently happens when we're called from SemaInit
9330 // when user-conversion overload fails. Figure out how to handle
9331 // those conditions and diagnose them well.
9332 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009333 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009334
9335 case ovl_fail_bad_target:
9336 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009337
9338 case ovl_fail_enable_if:
9339 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009340 }
John McCalld3224162010-01-08 00:58:21 +00009341}
9342
Richard Smith17c00b42014-11-12 01:24:00 +00009343static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009344 // Desugar the type of the surrogate down to a function type,
9345 // retaining as many typedefs as possible while still showing
9346 // the function type (and, therefore, its parameter types).
9347 QualType FnType = Cand->Surrogate->getConversionType();
9348 bool isLValueReference = false;
9349 bool isRValueReference = false;
9350 bool isPointer = false;
9351 if (const LValueReferenceType *FnTypeRef =
9352 FnType->getAs<LValueReferenceType>()) {
9353 FnType = FnTypeRef->getPointeeType();
9354 isLValueReference = true;
9355 } else if (const RValueReferenceType *FnTypeRef =
9356 FnType->getAs<RValueReferenceType>()) {
9357 FnType = FnTypeRef->getPointeeType();
9358 isRValueReference = true;
9359 }
9360 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9361 FnType = FnTypePtr->getPointeeType();
9362 isPointer = true;
9363 }
9364 // Desugar down to a function type.
9365 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9366 // Reconstruct the pointer/reference as appropriate.
9367 if (isPointer) FnType = S.Context.getPointerType(FnType);
9368 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9369 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9370
9371 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9372 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009373 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009374}
9375
Richard Smith17c00b42014-11-12 01:24:00 +00009376static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9377 SourceLocation OpLoc,
9378 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009379 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009380 std::string TypeStr("operator");
9381 TypeStr += Opc;
9382 TypeStr += "(";
9383 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009384 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009385 TypeStr += ")";
9386 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9387 } else {
9388 TypeStr += ", ";
9389 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9390 TypeStr += ")";
9391 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9392 }
9393}
9394
Richard Smith17c00b42014-11-12 01:24:00 +00009395static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9396 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009397 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009398 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9399 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009400 if (ICS.isBad()) break; // all meaningless after first invalid
9401 if (!ICS.isAmbiguous()) continue;
9402
John McCall5c32be02010-08-24 20:38:10 +00009403 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009404 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009405 }
9406}
9407
Larisse Voufo98b20f12013-07-19 23:00:19 +00009408static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009409 if (Cand->Function)
9410 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009411 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009412 return Cand->Surrogate->getLocation();
9413 return SourceLocation();
9414}
9415
Larisse Voufo98b20f12013-07-19 23:00:19 +00009416static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009417 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009418 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009419 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009420
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009421 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009422 case Sema::TDK_Incomplete:
9423 return 1;
9424
9425 case Sema::TDK_Underqualified:
9426 case Sema::TDK_Inconsistent:
9427 return 2;
9428
9429 case Sema::TDK_SubstitutionFailure:
9430 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009431 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009432 return 3;
9433
9434 case Sema::TDK_InstantiationDepth:
9435 case Sema::TDK_FailedOverloadResolution:
9436 return 4;
9437
9438 case Sema::TDK_InvalidExplicitArguments:
9439 return 5;
9440
9441 case Sema::TDK_TooManyArguments:
9442 case Sema::TDK_TooFewArguments:
9443 return 6;
9444 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009445 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009446}
9447
Richard Smith17c00b42014-11-12 01:24:00 +00009448namespace {
John McCallad2587a2010-01-12 00:48:53 +00009449struct CompareOverloadCandidatesForDisplay {
9450 Sema &S;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009451 size_t NumArgs;
9452
9453 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9454 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009455
9456 bool operator()(const OverloadCandidate *L,
9457 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009458 // Fast-path this check.
9459 if (L == R) return false;
9460
John McCall12f97bc2010-01-08 04:41:39 +00009461 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009462 if (L->Viable) {
9463 if (!R->Viable) return true;
9464
9465 // TODO: introduce a tri-valued comparison for overload
9466 // candidates. Would be more worthwhile if we had a sort
9467 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009468 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9469 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009470 } else if (R->Viable)
9471 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009472
John McCall3712d9e2010-01-15 23:32:50 +00009473 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009474
John McCall3712d9e2010-01-15 23:32:50 +00009475 // Criteria by which we can sort non-viable candidates:
9476 if (!L->Viable) {
9477 // 1. Arity mismatches come after other candidates.
9478 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009479 L->FailureKind == ovl_fail_too_few_arguments) {
9480 if (R->FailureKind == ovl_fail_too_many_arguments ||
9481 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009482 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9483 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9484 if (LDist == RDist) {
9485 if (L->FailureKind == R->FailureKind)
9486 // Sort non-surrogates before surrogates.
9487 return !L->IsSurrogate && R->IsSurrogate;
9488 // Sort candidates requiring fewer parameters than there were
9489 // arguments given after candidates requiring more parameters
9490 // than there were arguments given.
9491 return L->FailureKind == ovl_fail_too_many_arguments;
9492 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009493 return LDist < RDist;
9494 }
John McCall3712d9e2010-01-15 23:32:50 +00009495 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009496 }
John McCall3712d9e2010-01-15 23:32:50 +00009497 if (R->FailureKind == ovl_fail_too_many_arguments ||
9498 R->FailureKind == ovl_fail_too_few_arguments)
9499 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009500
John McCallfe796dd2010-01-23 05:17:32 +00009501 // 2. Bad conversions come first and are ordered by the number
9502 // of bad conversions and quality of good conversions.
9503 if (L->FailureKind == ovl_fail_bad_conversion) {
9504 if (R->FailureKind != ovl_fail_bad_conversion)
9505 return true;
9506
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009507 // The conversion that can be fixed with a smaller number of changes,
9508 // comes first.
9509 unsigned numLFixes = L->Fix.NumConversionsFixed;
9510 unsigned numRFixes = R->Fix.NumConversionsFixed;
9511 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9512 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009513 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009514 if (numLFixes < numRFixes)
9515 return true;
9516 else
9517 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009518 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009519
John McCallfe796dd2010-01-23 05:17:32 +00009520 // If there's any ordering between the defined conversions...
9521 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009522 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009523
9524 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009525 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009526 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009527 switch (CompareImplicitConversionSequences(S,
9528 L->Conversions[I],
9529 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009530 case ImplicitConversionSequence::Better:
9531 leftBetter++;
9532 break;
9533
9534 case ImplicitConversionSequence::Worse:
9535 leftBetter--;
9536 break;
9537
9538 case ImplicitConversionSequence::Indistinguishable:
9539 break;
9540 }
9541 }
9542 if (leftBetter > 0) return true;
9543 if (leftBetter < 0) return false;
9544
9545 } else if (R->FailureKind == ovl_fail_bad_conversion)
9546 return false;
9547
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009548 if (L->FailureKind == ovl_fail_bad_deduction) {
9549 if (R->FailureKind != ovl_fail_bad_deduction)
9550 return true;
9551
9552 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9553 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009554 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009555 } else if (R->FailureKind == ovl_fail_bad_deduction)
9556 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009557
John McCall3712d9e2010-01-15 23:32:50 +00009558 // TODO: others?
9559 }
9560
9561 // Sort everything else by location.
9562 SourceLocation LLoc = GetLocationForCandidate(L);
9563 SourceLocation RLoc = GetLocationForCandidate(R);
9564
9565 // Put candidates without locations (e.g. builtins) at the end.
9566 if (LLoc.isInvalid()) return false;
9567 if (RLoc.isInvalid()) return true;
9568
9569 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009570 }
9571};
Richard Smith17c00b42014-11-12 01:24:00 +00009572}
John McCall12f97bc2010-01-08 04:41:39 +00009573
John McCallfe796dd2010-01-23 05:17:32 +00009574/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009575/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009576static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9577 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009578 assert(!Cand->Viable);
9579
9580 // Don't do anything on failures other than bad conversion.
9581 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9582
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009583 // We only want the FixIts if all the arguments can be corrected.
9584 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009585 // Use a implicit copy initialization to check conversion fixes.
9586 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009587
John McCallfe796dd2010-01-23 05:17:32 +00009588 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009589 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009590 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009591 while (true) {
9592 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9593 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009594 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009595 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009596 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009597 }
John McCallfe796dd2010-01-23 05:17:32 +00009598 }
9599
9600 if (ConvIdx == ConvCount)
9601 return;
9602
John McCall65eb8792010-02-25 01:37:24 +00009603 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9604 "remaining conversion is initialized?");
9605
Douglas Gregoradc7a702010-04-16 17:45:54 +00009606 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009607 // operation somehow.
9608 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009609
9610 const FunctionProtoType* Proto;
9611 unsigned ArgIdx = ConvIdx;
9612
9613 if (Cand->IsSurrogate) {
9614 QualType ConvType
9615 = Cand->Surrogate->getConversionType().getNonReferenceType();
9616 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9617 ConvType = ConvPtrType->getPointeeType();
9618 Proto = ConvType->getAs<FunctionProtoType>();
9619 ArgIdx--;
9620 } else if (Cand->Function) {
9621 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9622 if (isa<CXXMethodDecl>(Cand->Function) &&
9623 !isa<CXXConstructorDecl>(Cand->Function))
9624 ArgIdx--;
9625 } else {
9626 // Builtin binary operator with a bad first conversion.
9627 assert(ConvCount <= 3);
9628 for (; ConvIdx != ConvCount; ++ConvIdx)
9629 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009630 = TryCopyInitialization(S, Args[ConvIdx],
9631 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009632 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009633 /*InOverloadResolution*/ true,
9634 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009635 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009636 return;
9637 }
9638
9639 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009640 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009641 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009642 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009643 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9644 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9645 /*InOverloadResolution=*/true,
9646 /*AllowObjCWritebackConversion=*/
9647 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009648 // Store the FixIt in the candidate if it exists.
9649 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009650 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009651 }
John McCallfe796dd2010-01-23 05:17:32 +00009652 else
9653 Cand->Conversions[ConvIdx].setEllipsis();
9654 }
9655}
9656
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009657/// PrintOverloadCandidates - When overload resolution fails, prints
9658/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009659/// set.
John McCall5c32be02010-08-24 20:38:10 +00009660void OverloadCandidateSet::NoteCandidates(Sema &S,
9661 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009662 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009663 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009664 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009665 // Sort the candidates by viability and position. Sorting directly would
9666 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009667 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009668 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9669 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009670 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009671 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009672 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009673 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009674 if (Cand->Function || Cand->IsSurrogate)
9675 Cands.push_back(Cand);
9676 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9677 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009678 }
9679 }
9680
John McCallad2587a2010-01-12 00:48:53 +00009681 std::sort(Cands.begin(), Cands.end(),
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009682 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009683
John McCall0d1da222010-01-12 00:44:57 +00009684 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009685
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009686 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009687 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009688 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009689 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9690 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009691
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009692 // Set an arbitrary limit on the number of candidate functions we'll spam
9693 // the user with. FIXME: This limit should depend on details of the
9694 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009695 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009696 break;
9697 }
9698 ++CandsShown;
9699
John McCalld3224162010-01-08 00:58:21 +00009700 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009701 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009702 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009703 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009704 else {
9705 assert(Cand->Viable &&
9706 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009707 // Generally we only see ambiguities including viable builtin
9708 // operators if overload resolution got screwed up by an
9709 // ambiguous user-defined conversion.
9710 //
9711 // FIXME: It's quite possible for different conversions to see
9712 // different ambiguities, though.
9713 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009714 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009715 ReportedAmbiguousConversions = true;
9716 }
John McCalld3224162010-01-08 00:58:21 +00009717
John McCall0d1da222010-01-12 00:44:57 +00009718 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009719 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009720 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009721 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009722
9723 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009724 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009725}
9726
Larisse Voufo98b20f12013-07-19 23:00:19 +00009727static SourceLocation
9728GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9729 return Cand->Specialization ? Cand->Specialization->getLocation()
9730 : SourceLocation();
9731}
9732
Richard Smith17c00b42014-11-12 01:24:00 +00009733namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009734struct CompareTemplateSpecCandidatesForDisplay {
9735 Sema &S;
9736 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9737
9738 bool operator()(const TemplateSpecCandidate *L,
9739 const TemplateSpecCandidate *R) {
9740 // Fast-path this check.
9741 if (L == R)
9742 return false;
9743
9744 // Assuming that both candidates are not matches...
9745
9746 // Sort by the ranking of deduction failures.
9747 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9748 return RankDeductionFailure(L->DeductionFailure) <
9749 RankDeductionFailure(R->DeductionFailure);
9750
9751 // Sort everything else by location.
9752 SourceLocation LLoc = GetLocationForCandidate(L);
9753 SourceLocation RLoc = GetLocationForCandidate(R);
9754
9755 // Put candidates without locations (e.g. builtins) at the end.
9756 if (LLoc.isInvalid())
9757 return false;
9758 if (RLoc.isInvalid())
9759 return true;
9760
9761 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9762 }
9763};
Richard Smith17c00b42014-11-12 01:24:00 +00009764}
Larisse Voufo98b20f12013-07-19 23:00:19 +00009765
9766/// Diagnose a template argument deduction failure.
9767/// We are treating these failures as overload failures due to bad
9768/// deductions.
9769void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9770 DiagnoseBadDeduction(S, Specialization, // pattern
9771 DeductionFailure, /*NumArgs=*/0);
9772}
9773
9774void TemplateSpecCandidateSet::destroyCandidates() {
9775 for (iterator i = begin(), e = end(); i != e; ++i) {
9776 i->DeductionFailure.Destroy();
9777 }
9778}
9779
9780void TemplateSpecCandidateSet::clear() {
9781 destroyCandidates();
9782 Candidates.clear();
9783}
9784
9785/// NoteCandidates - When no template specialization match is found, prints
9786/// diagnostic messages containing the non-matching specializations that form
9787/// the candidate set.
9788/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9789/// OCD == OCD_AllCandidates and Cand->Viable == false.
9790void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9791 // Sort the candidates by position (assuming no candidate is a match).
9792 // Sorting directly would be prohibitive, so we make a set of pointers
9793 // and sort those.
9794 SmallVector<TemplateSpecCandidate *, 32> Cands;
9795 Cands.reserve(size());
9796 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9797 if (Cand->Specialization)
9798 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009799 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009800 // in general, want to list every possible builtin candidate.
9801 }
9802
9803 std::sort(Cands.begin(), Cands.end(),
9804 CompareTemplateSpecCandidatesForDisplay(S));
9805
9806 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9807 // for generalization purposes (?).
9808 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9809
9810 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9811 unsigned CandsShown = 0;
9812 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9813 TemplateSpecCandidate *Cand = *I;
9814
9815 // Set an arbitrary limit on the number of candidates we'll spam
9816 // the user with. FIXME: This limit should depend on details of the
9817 // candidate list.
9818 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9819 break;
9820 ++CandsShown;
9821
9822 assert(Cand->Specialization &&
9823 "Non-matching built-in candidates are not added to Cands.");
9824 Cand->NoteDeductionFailure(S);
9825 }
9826
9827 if (I != E)
9828 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9829}
9830
Douglas Gregorb491ed32011-02-19 21:32:49 +00009831// [PossiblyAFunctionType] --> [Return]
9832// NonFunctionType --> NonFunctionType
9833// R (A) --> R(A)
9834// R (*)(A) --> R (A)
9835// R (&)(A) --> R (A)
9836// R (S::*)(A) --> R (A)
9837QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9838 QualType Ret = PossiblyAFunctionType;
9839 if (const PointerType *ToTypePtr =
9840 PossiblyAFunctionType->getAs<PointerType>())
9841 Ret = ToTypePtr->getPointeeType();
9842 else if (const ReferenceType *ToTypeRef =
9843 PossiblyAFunctionType->getAs<ReferenceType>())
9844 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009845 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009846 PossiblyAFunctionType->getAs<MemberPointerType>())
9847 Ret = MemTypePtr->getPointeeType();
9848 Ret =
9849 Context.getCanonicalType(Ret).getUnqualifiedType();
9850 return Ret;
9851}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009852
Richard Smith17c00b42014-11-12 01:24:00 +00009853namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009854// A helper class to help with address of function resolution
9855// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +00009856class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009857 Sema& S;
9858 Expr* SourceExpr;
9859 const QualType& TargetType;
9860 QualType TargetFunctionType; // Extracted function type from target type
9861
9862 bool Complain;
9863 //DeclAccessPair& ResultFunctionAccessPair;
9864 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009865
Douglas Gregorb491ed32011-02-19 21:32:49 +00009866 bool TargetTypeIsNonStaticMemberFunction;
9867 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009868 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009869
Douglas Gregorb491ed32011-02-19 21:32:49 +00009870 OverloadExpr::FindResult OvlExprInfo;
9871 OverloadExpr *OvlExpr;
9872 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009873 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009874 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009875
Douglas Gregorb491ed32011-02-19 21:32:49 +00009876public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009877 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9878 const QualType &TargetType, bool Complain)
9879 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9880 Complain(Complain), Context(S.getASTContext()),
9881 TargetTypeIsNonStaticMemberFunction(
9882 !!TargetType->getAs<MemberPointerType>()),
9883 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009884 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009885 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9886 OvlExpr(OvlExprInfo.Expression),
9887 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009888 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009889
David Majnemera4f7c7a2013-08-01 06:13:59 +00009890 if (TargetFunctionType->isFunctionType()) {
9891 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9892 if (!UME->isImplicitAccess() &&
9893 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9894 StaticMemberFunctionFromBoundPointer = true;
9895 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9896 DeclAccessPair dap;
9897 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9898 OvlExpr, false, &dap)) {
9899 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9900 if (!Method->isStatic()) {
9901 // If the target type is a non-function type and the function found
9902 // is a non-static member function, pretend as if that was the
9903 // target, it's the only possible type to end up with.
9904 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009905
David Majnemera4f7c7a2013-08-01 06:13:59 +00009906 // And skip adding the function if its not in the proper form.
9907 // We'll diagnose this due to an empty set of functions.
9908 if (!OvlExprInfo.HasFormOfMemberPointer)
9909 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009910 }
9911
David Majnemera4f7c7a2013-08-01 06:13:59 +00009912 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009913 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009914 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009915 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009916
9917 if (OvlExpr->hasExplicitTemplateArgs())
9918 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009919
Douglas Gregorb491ed32011-02-19 21:32:49 +00009920 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9921 // C++ [over.over]p4:
9922 // If more than one function is selected, [...]
9923 if (Matches.size() > 1) {
9924 if (FoundNonTemplateFunction)
9925 EliminateAllTemplateMatches();
9926 else
9927 EliminateAllExceptMostSpecializedTemplate();
9928 }
9929 }
9930 }
9931
9932private:
9933 bool isTargetTypeAFunction() const {
9934 return TargetFunctionType->isFunctionType();
9935 }
9936
9937 // [ToType] [Return]
9938
9939 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9940 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9941 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9942 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9943 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9944 }
9945
9946 // return true if any matching specializations were found
9947 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9948 const DeclAccessPair& CurAccessFunPair) {
9949 if (CXXMethodDecl *Method
9950 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9951 // Skip non-static function templates when converting to pointer, and
9952 // static when converting to member pointer.
9953 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9954 return false;
9955 }
9956 else if (TargetTypeIsNonStaticMemberFunction)
9957 return false;
9958
9959 // C++ [over.over]p2:
9960 // If the name is a function template, template argument deduction is
9961 // done (14.8.2.2), and if the argument deduction succeeds, the
9962 // resulting template argument list is used to generate a single
9963 // function template specialization, which is added to the set of
9964 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +00009965 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009966 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009967 if (Sema::TemplateDeductionResult Result
9968 = S.DeduceTemplateArguments(FunctionTemplate,
9969 &OvlExplicitTemplateArgs,
9970 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009971 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009972 // Make a note of the failed deduction for diagnostics.
9973 FailedCandidates.addCandidate()
9974 .set(FunctionTemplate->getTemplatedDecl(),
9975 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009976 return false;
9977 }
9978
Douglas Gregor19a41f12013-04-17 08:45:07 +00009979 // Template argument deduction ensures that we have an exact match or
9980 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009981 // This function template specicalization works.
9982 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009983 assert(S.isSameOrCompatibleFunctionType(
9984 Context.getCanonicalType(Specialization->getType()),
9985 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009986 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9987 return true;
9988 }
9989
9990 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9991 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009992 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009993 // Skip non-static functions when converting to pointer, and static
9994 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009995 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9996 return false;
9997 }
9998 else if (TargetTypeIsNonStaticMemberFunction)
9999 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010000
Chandler Carruthc25c6ee2009-12-29 06:17:27 +000010001 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010002 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010003 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010004 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010005 return false;
10006
Richard Smith2a7d4812013-05-04 07:00:32 +000010007 // If any candidate has a placeholder return type, trigger its deduction
10008 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010009 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010010 FunDecl->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010011 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
10012 return false;
10013
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000010014 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010015 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10016 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +000010017 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
10018 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010019 Matches.push_back(std::make_pair(CurAccessFunPair,
10020 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010021 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010022 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010023 }
Mike Stump11289f42009-09-09 15:08:12 +000010024 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010025
10026 return false;
10027 }
10028
10029 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10030 bool Ret = false;
10031
10032 // If the overload expression doesn't have the form of a pointer to
10033 // member, don't try to convert it to a pointer-to-member type.
10034 if (IsInvalidFormOfPointerToMemberFunction())
10035 return false;
10036
10037 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10038 E = OvlExpr->decls_end();
10039 I != E; ++I) {
10040 // Look through any using declarations to find the underlying function.
10041 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10042
10043 // C++ [over.over]p3:
10044 // Non-member functions and static member functions match
10045 // targets of type "pointer-to-function" or "reference-to-function."
10046 // Nonstatic member functions match targets of
10047 // type "pointer-to-member-function."
10048 // Note that according to DR 247, the containing class does not matter.
10049 if (FunctionTemplateDecl *FunctionTemplate
10050 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10051 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10052 Ret = true;
10053 }
10054 // If we have explicit template arguments supplied, skip non-templates.
10055 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10056 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10057 Ret = true;
10058 }
10059 assert(Ret || Matches.empty());
10060 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010061 }
10062
Douglas Gregorb491ed32011-02-19 21:32:49 +000010063 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010064 // [...] and any given function template specialization F1 is
10065 // eliminated if the set contains a second function template
10066 // specialization whose function template is more specialized
10067 // than the function template of F1 according to the partial
10068 // ordering rules of 14.5.5.2.
10069
10070 // The algorithm specified above is quadratic. We instead use a
10071 // two-pass algorithm (similar to the one used to identify the
10072 // best viable function in an overload set) that identifies the
10073 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010074
10075 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10076 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10077 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010078
Larisse Voufo98b20f12013-07-19 23:00:19 +000010079 // TODO: It looks like FailedCandidates does not serve much purpose
10080 // here, since the no_viable diagnostic has index 0.
10081 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010082 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010083 SourceExpr->getLocStart(), S.PDiag(),
10084 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10085 .second->getDeclName(),
10086 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10087 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010088
Douglas Gregorb491ed32011-02-19 21:32:49 +000010089 if (Result != MatchesCopy.end()) {
10090 // Make it the first and only element
10091 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10092 Matches[0].second = cast<FunctionDecl>(*Result);
10093 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +000010094 }
10095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010096
Douglas Gregorb491ed32011-02-19 21:32:49 +000010097 void EliminateAllTemplateMatches() {
10098 // [...] any function template specializations in the set are
10099 // eliminated if the set also contains a non-template function, [...]
10100 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010101 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010102 ++I;
10103 else {
10104 Matches[I] = Matches[--N];
10105 Matches.set_size(N);
10106 }
10107 }
10108 }
10109
10110public:
10111 void ComplainNoMatchesFound() const {
10112 assert(Matches.empty());
10113 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10114 << OvlExpr->getName() << TargetFunctionType
10115 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010116 if (FailedCandidates.empty())
10117 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10118 else {
10119 // We have some deduction failure messages. Use them to diagnose
10120 // the function templates, and diagnose the non-template candidates
10121 // normally.
10122 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10123 IEnd = OvlExpr->decls_end();
10124 I != IEnd; ++I)
10125 if (FunctionDecl *Fun =
10126 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10127 S.NoteOverloadCandidate(Fun, TargetFunctionType);
10128 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10129 }
10130 }
10131
Douglas Gregorb491ed32011-02-19 21:32:49 +000010132 bool IsInvalidFormOfPointerToMemberFunction() const {
10133 return TargetTypeIsNonStaticMemberFunction &&
10134 !OvlExprInfo.HasFormOfMemberPointer;
10135 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010136
Douglas Gregorb491ed32011-02-19 21:32:49 +000010137 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10138 // TODO: Should we condition this on whether any functions might
10139 // have matched, or is it more appropriate to do that in callers?
10140 // TODO: a fixit wouldn't hurt.
10141 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10142 << TargetType << OvlExpr->getSourceRange();
10143 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010144
10145 bool IsStaticMemberFunctionFromBoundPointer() const {
10146 return StaticMemberFunctionFromBoundPointer;
10147 }
10148
10149 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10150 S.Diag(OvlExpr->getLocStart(),
10151 diag::err_invalid_form_pointer_member_function)
10152 << OvlExpr->getSourceRange();
10153 }
10154
Douglas Gregorb491ed32011-02-19 21:32:49 +000010155 void ComplainOfInvalidConversion() const {
10156 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10157 << OvlExpr->getName() << TargetType;
10158 }
10159
10160 void ComplainMultipleMatchesFound() const {
10161 assert(Matches.size() > 1);
10162 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10163 << OvlExpr->getName()
10164 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +000010165 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010166 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010167
10168 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10169
Douglas Gregorb491ed32011-02-19 21:32:49 +000010170 int getNumMatches() const { return Matches.size(); }
10171
10172 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010173 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010174 return Matches[0].second;
10175 }
10176
10177 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010178 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010179 return &Matches[0].first;
10180 }
10181};
Richard Smith17c00b42014-11-12 01:24:00 +000010182}
10183
Douglas Gregorb491ed32011-02-19 21:32:49 +000010184/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10185/// an overloaded function (C++ [over.over]), where @p From is an
10186/// expression with overloaded function type and @p ToType is the type
10187/// we're trying to resolve to. For example:
10188///
10189/// @code
10190/// int f(double);
10191/// int f(int);
10192///
10193/// int (*pfd)(double) = f; // selects f(double)
10194/// @endcode
10195///
10196/// This routine returns the resulting FunctionDecl if it could be
10197/// resolved, and NULL otherwise. When @p Complain is true, this
10198/// routine will emit diagnostics if there is an error.
10199FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010200Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10201 QualType TargetType,
10202 bool Complain,
10203 DeclAccessPair &FoundResult,
10204 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010205 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010206
10207 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10208 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010209 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010210 FunctionDecl *Fn = nullptr;
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010211 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010212 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10213 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10214 else
10215 Resolver.ComplainNoMatchesFound();
10216 }
10217 else if (NumMatches > 1 && Complain)
10218 Resolver.ComplainMultipleMatchesFound();
10219 else if (NumMatches == 1) {
10220 Fn = Resolver.getMatchingFunctionDecl();
10221 assert(Fn);
10222 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010223 if (Complain) {
10224 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10225 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10226 else
10227 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10228 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010229 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010230
10231 if (pHadMultipleCandidates)
10232 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010233 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010234}
10235
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010236/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010237/// resolve that overloaded function expression down to a single function.
10238///
10239/// This routine can only resolve template-ids that refer to a single function
10240/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010241/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010242/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010243///
10244/// If no template-ids are found, no diagnostics are emitted and NULL is
10245/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010246FunctionDecl *
10247Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10248 bool Complain,
10249 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010250 // C++ [over.over]p1:
10251 // [...] [Note: any redundant set of parentheses surrounding the
10252 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010253 // C++ [over.over]p1:
10254 // [...] The overloaded function name can be preceded by the &
10255 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010256
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010257 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010258 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010259 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010260
10261 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010262 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010263 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010264
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010265 // Look through all of the overloaded functions, searching for one
10266 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010267 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010268 for (UnresolvedSetIterator I = ovl->decls_begin(),
10269 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010270 // C++0x [temp.arg.explicit]p3:
10271 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010272 // where deduction is not done, if a template argument list is
10273 // specified and it, along with any default template arguments,
10274 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010275 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010276 FunctionTemplateDecl *FunctionTemplate
10277 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010278
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010279 // C++ [over.over]p2:
10280 // If the name is a function template, template argument deduction is
10281 // done (14.8.2.2), and if the argument deduction succeeds, the
10282 // resulting template argument list is used to generate a single
10283 // function template specialization, which is added to the set of
10284 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010285 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010286 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010287 if (TemplateDeductionResult Result
10288 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010289 Specialization, Info,
10290 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010291 // Make a note of the failed deduction for diagnostics.
10292 // TODO: Actually use the failed-deduction info?
10293 FailedCandidates.addCandidate()
10294 .set(FunctionTemplate->getTemplatedDecl(),
10295 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010296 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010297 }
10298
John McCall0009fcc2011-04-26 20:42:42 +000010299 assert(Specialization && "no specialization and no error?");
10300
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010301 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010302 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010303 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010304 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10305 << ovl->getName();
10306 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010307 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010308 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010309 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010310
John McCall0009fcc2011-04-26 20:42:42 +000010311 Matched = Specialization;
10312 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010314
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010315 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010316 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010317 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010318 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010319
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010320 return Matched;
10321}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010322
Douglas Gregor1beec452011-03-12 01:48:56 +000010323
10324
10325
John McCall50a2c2c2011-10-11 23:14:30 +000010326// Resolve and fix an overloaded expression that can be resolved
10327// because it identifies a single function template specialization.
10328//
Douglas Gregor1beec452011-03-12 01:48:56 +000010329// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010330//
10331// Return true if it was logically possible to so resolve the
10332// expression, regardless of whether or not it succeeded. Always
10333// returns true if 'complain' is set.
10334bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10335 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10336 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010337 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010338 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010339 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010340
John McCall50a2c2c2011-10-11 23:14:30 +000010341 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010342
John McCall0009fcc2011-04-26 20:42:42 +000010343 DeclAccessPair found;
10344 ExprResult SingleFunctionExpression;
10345 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10346 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010347 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010348 SrcExpr = ExprError();
10349 return true;
10350 }
John McCall0009fcc2011-04-26 20:42:42 +000010351
10352 // It is only correct to resolve to an instance method if we're
10353 // resolving a form that's permitted to be a pointer to member.
10354 // Otherwise we'll end up making a bound member expression, which
10355 // is illegal in all the contexts we resolve like this.
10356 if (!ovl.HasFormOfMemberPointer &&
10357 isa<CXXMethodDecl>(fn) &&
10358 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010359 if (!complain) return false;
10360
10361 Diag(ovl.Expression->getExprLoc(),
10362 diag::err_bound_member_function)
10363 << 0 << ovl.Expression->getSourceRange();
10364
10365 // TODO: I believe we only end up here if there's a mix of
10366 // static and non-static candidates (otherwise the expression
10367 // would have 'bound member' type, not 'overload' type).
10368 // Ideally we would note which candidate was chosen and why
10369 // the static candidates were rejected.
10370 SrcExpr = ExprError();
10371 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010372 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010373
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010374 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010375 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010376 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010377
10378 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010379 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010380 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010381 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010382 if (SingleFunctionExpression.isInvalid()) {
10383 SrcExpr = ExprError();
10384 return true;
10385 }
10386 }
John McCall0009fcc2011-04-26 20:42:42 +000010387 }
10388
10389 if (!SingleFunctionExpression.isUsable()) {
10390 if (complain) {
10391 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10392 << ovl.Expression->getName()
10393 << DestTypeForComplaining
10394 << OpRangeForComplaining
10395 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010396 NoteAllOverloadCandidates(SrcExpr.get());
10397
10398 SrcExpr = ExprError();
10399 return true;
10400 }
10401
10402 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010403 }
10404
John McCall50a2c2c2011-10-11 23:14:30 +000010405 SrcExpr = SingleFunctionExpression;
10406 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010407}
10408
Douglas Gregorcabea402009-09-22 15:41:20 +000010409/// \brief Add a single candidate to the overload set.
10410static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010411 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010412 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010413 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010414 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010415 bool PartialOverloading,
10416 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010417 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010418 if (isa<UsingShadowDecl>(Callee))
10419 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10420
Douglas Gregorcabea402009-09-22 15:41:20 +000010421 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010422 if (ExplicitTemplateArgs) {
10423 assert(!KnownValid && "Explicit template arguments?");
10424 return;
10425 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010426 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10427 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010428 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010429 return;
John McCalld14a8642009-11-21 08:51:07 +000010430 }
10431
10432 if (FunctionTemplateDecl *FuncTemplate
10433 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010434 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010435 ExplicitTemplateArgs, Args, CandidateSet,
10436 /*SuppressUsedConversions=*/false,
10437 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010438 return;
10439 }
10440
Richard Smith95ce4f62011-06-26 22:19:54 +000010441 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010442}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010443
Douglas Gregorcabea402009-09-22 15:41:20 +000010444/// \brief Add the overload candidates named by callee and/or found by argument
10445/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010446void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010447 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010448 OverloadCandidateSet &CandidateSet,
10449 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010450
10451#ifndef NDEBUG
10452 // Verify that ArgumentDependentLookup is consistent with the rules
10453 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010454 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010455 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10456 // and let Y be the lookup set produced by argument dependent
10457 // lookup (defined as follows). If X contains
10458 //
10459 // -- a declaration of a class member, or
10460 //
10461 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010462 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010463 //
10464 // -- a declaration that is neither a function or a function
10465 // template
10466 //
10467 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010468
John McCall57500772009-12-16 12:17:52 +000010469 if (ULE->requiresADL()) {
10470 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10471 E = ULE->decls_end(); I != E; ++I) {
10472 assert(!(*I)->getDeclContext()->isRecord());
10473 assert(isa<UsingShadowDecl>(*I) ||
10474 !(*I)->getDeclContext()->isFunctionOrMethod());
10475 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010476 }
10477 }
10478#endif
10479
John McCall57500772009-12-16 12:17:52 +000010480 // It would be nice to avoid this copy.
10481 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010482 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010483 if (ULE->hasExplicitTemplateArgs()) {
10484 ULE->copyTemplateArgumentsInto(TABuffer);
10485 ExplicitTemplateArgs = &TABuffer;
10486 }
10487
10488 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10489 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010490 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10491 CandidateSet, PartialOverloading,
10492 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010493
John McCall57500772009-12-16 12:17:52 +000010494 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010495 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010496 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010497 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010498}
John McCalld681c392009-12-16 08:11:27 +000010499
Richard Smith0603bbb2013-06-12 22:56:54 +000010500/// Determine whether a declaration with the specified name could be moved into
10501/// a different namespace.
10502static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10503 switch (Name.getCXXOverloadedOperator()) {
10504 case OO_New: case OO_Array_New:
10505 case OO_Delete: case OO_Array_Delete:
10506 return false;
10507
10508 default:
10509 return true;
10510 }
10511}
10512
Richard Smith998a5912011-06-05 22:42:48 +000010513/// Attempt to recover from an ill-formed use of a non-dependent name in a
10514/// template, where the non-dependent name was declared after the template
10515/// was defined. This is common in code written for a compilers which do not
10516/// correctly implement two-stage name lookup.
10517///
10518/// Returns true if a viable candidate was found and a diagnostic was issued.
10519static bool
10520DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10521 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010522 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010523 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010524 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010525 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10526 return false;
10527
10528 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010529 if (DC->isTransparentContext())
10530 continue;
10531
Richard Smith998a5912011-06-05 22:42:48 +000010532 SemaRef.LookupQualifiedName(R, DC);
10533
10534 if (!R.empty()) {
10535 R.suppressDiagnostics();
10536
10537 if (isa<CXXRecordDecl>(DC)) {
10538 // Don't diagnose names we find in classes; we get much better
10539 // diagnostics for these from DiagnoseEmptyLookup.
10540 R.clear();
10541 return false;
10542 }
10543
Richard Smith100b24a2014-04-17 01:52:14 +000010544 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010545 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10546 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010547 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010548 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010549
10550 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010551 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010552 // No viable functions. Don't bother the user with notes for functions
10553 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010554 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010555 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010556 }
Richard Smith998a5912011-06-05 22:42:48 +000010557
10558 // Find the namespaces where ADL would have looked, and suggest
10559 // declaring the function there instead.
10560 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10561 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010562 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010563 AssociatedNamespaces,
10564 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010565 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010566 if (canBeDeclaredInNamespace(R.getLookupName())) {
10567 DeclContext *Std = SemaRef.getStdNamespace();
10568 for (Sema::AssociatedNamespaceSet::iterator
10569 it = AssociatedNamespaces.begin(),
10570 end = AssociatedNamespaces.end(); it != end; ++it) {
10571 // Never suggest declaring a function within namespace 'std'.
10572 if (Std && Std->Encloses(*it))
10573 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010574
Richard Smith0603bbb2013-06-12 22:56:54 +000010575 // Never suggest declaring a function within a namespace with a
10576 // reserved name, like __gnu_cxx.
10577 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10578 if (NS &&
10579 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10580 continue;
10581
10582 SuggestedNamespaces.insert(*it);
10583 }
Richard Smith998a5912011-06-05 22:42:48 +000010584 }
10585
10586 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10587 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010588 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010589 SemaRef.Diag(Best->Function->getLocation(),
10590 diag::note_not_found_by_two_phase_lookup)
10591 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010592 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010593 SemaRef.Diag(Best->Function->getLocation(),
10594 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010595 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010596 } else {
10597 // FIXME: It would be useful to list the associated namespaces here,
10598 // but the diagnostics infrastructure doesn't provide a way to produce
10599 // a localized representation of a list of items.
10600 SemaRef.Diag(Best->Function->getLocation(),
10601 diag::note_not_found_by_two_phase_lookup)
10602 << R.getLookupName() << 2;
10603 }
10604
10605 // Try to recover by calling this function.
10606 return true;
10607 }
10608
10609 R.clear();
10610 }
10611
10612 return false;
10613}
10614
10615/// Attempt to recover from ill-formed use of a non-dependent operator in a
10616/// template, where the non-dependent operator was declared after the template
10617/// was defined.
10618///
10619/// Returns true if a viable candidate was found and a diagnostic was issued.
10620static bool
10621DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10622 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010623 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010624 DeclarationName OpName =
10625 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10626 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10627 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010628 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010629 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010630}
10631
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010632namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010633class BuildRecoveryCallExprRAII {
10634 Sema &SemaRef;
10635public:
10636 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10637 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10638 SemaRef.IsBuildingRecoveryCallExpr = true;
10639 }
10640
10641 ~BuildRecoveryCallExprRAII() {
10642 SemaRef.IsBuildingRecoveryCallExpr = false;
10643 }
10644};
10645
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010646}
10647
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010648static std::unique_ptr<CorrectionCandidateCallback>
10649MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10650 bool HasTemplateArgs, bool AllowTypoCorrection) {
10651 if (!AllowTypoCorrection)
10652 return llvm::make_unique<NoTypoCorrectionCCC>();
10653 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10654 HasTemplateArgs, ME);
10655}
10656
John McCalld681c392009-12-16 08:11:27 +000010657/// Attempts to recover from a call where no functions were found.
10658///
10659/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010660static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010661BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010662 UnresolvedLookupExpr *ULE,
10663 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010664 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010665 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010666 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010667 // Do not try to recover if it is already building a recovery call.
10668 // This stops infinite loops for template instantiations like
10669 //
10670 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10671 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10672 //
10673 if (SemaRef.IsBuildingRecoveryCallExpr)
10674 return ExprError();
10675 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010676
10677 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010678 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010679 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010680
John McCall57500772009-12-16 12:17:52 +000010681 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010682 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010683 if (ULE->hasExplicitTemplateArgs()) {
10684 ULE->copyTemplateArgumentsInto(TABuffer);
10685 ExplicitTemplateArgs = &TABuffer;
10686 }
10687
John McCalld681c392009-12-16 08:11:27 +000010688 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10689 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +000010690 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000010691 OverloadCandidateSet::CSK_Normal,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010692 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +000010693 (!EmptyLookup ||
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010694 SemaRef.DiagnoseEmptyLookup(
10695 S, SS, R,
10696 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10697 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10698 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010699 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010700
John McCall57500772009-12-16 12:17:52 +000010701 assert(!R.empty() && "lookup results empty despite recovery");
10702
10703 // Build an implicit member call if appropriate. Just drop the
10704 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010705 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010706 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010707 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10708 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010709 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010710 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010711 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010712 else
10713 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10714
10715 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010716 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010717
10718 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010719 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010720 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010721 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010722 MultiExprArg(Args.data(), Args.size()),
10723 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010724}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010725
Sam Panzer0f384432012-08-21 00:52:01 +000010726/// \brief Constructs and populates an OverloadedCandidateSet from
10727/// the given function.
10728/// \returns true when an the ExprResult output parameter has been set.
10729bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10730 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010731 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010732 SourceLocation RParenLoc,
10733 OverloadCandidateSet *CandidateSet,
10734 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010735#ifndef NDEBUG
10736 if (ULE->requiresADL()) {
10737 // To do ADL, we must have found an unqualified name.
10738 assert(!ULE->getQualifier() && "qualified name with ADL");
10739
10740 // We don't perform ADL for implicit declarations of builtins.
10741 // Verify that this was correctly set up.
10742 FunctionDecl *F;
10743 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10744 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10745 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010746 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010747
John McCall57500772009-12-16 12:17:52 +000010748 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010749 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010750 }
John McCall57500772009-12-16 12:17:52 +000010751#endif
10752
John McCall4124c492011-10-17 18:40:02 +000010753 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010754 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010755 *Result = ExprError();
10756 return true;
10757 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010758
John McCall57500772009-12-16 12:17:52 +000010759 // Add the functions denoted by the callee to the set of candidate
10760 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010761 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010762
10763 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +000010764 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10765 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +000010766 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010767 // In Microsoft mode, if we are inside a template class member function then
10768 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +000010769 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010770 // classes.
Alp Tokerbfa39342014-01-14 12:51:41 +000010771 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +000010772 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010773 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010774 Context.DependentTy, VK_RValue,
10775 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010776 CE->setTypeDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010777 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000010778 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010779 }
Sam Panzer0f384432012-08-21 00:52:01 +000010780 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +000010781 }
John McCalld681c392009-12-16 08:11:27 +000010782
John McCall4124c492011-10-17 18:40:02 +000010783 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010784 return false;
10785}
John McCall4124c492011-10-17 18:40:02 +000010786
Sam Panzer0f384432012-08-21 00:52:01 +000010787/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10788/// the completed call expression. If overload resolution fails, emits
10789/// diagnostics and returns ExprError()
10790static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10791 UnresolvedLookupExpr *ULE,
10792 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010793 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010794 SourceLocation RParenLoc,
10795 Expr *ExecConfig,
10796 OverloadCandidateSet *CandidateSet,
10797 OverloadCandidateSet::iterator *Best,
10798 OverloadingResult OverloadResult,
10799 bool AllowTypoCorrection) {
10800 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010801 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010802 RParenLoc, /*EmptyLookup=*/true,
10803 AllowTypoCorrection);
10804
10805 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010806 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010807 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010808 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010809 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10810 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010811 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010812 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10813 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010814 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010815
Richard Smith998a5912011-06-05 22:42:48 +000010816 case OR_No_Viable_Function: {
10817 // Try to recover by looking for viable functions which the user might
10818 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010819 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010820 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010821 /*EmptyLookup=*/false,
10822 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010823 if (!Recovery.isInvalid())
10824 return Recovery;
10825
Sam Panzer0f384432012-08-21 00:52:01 +000010826 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010827 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010828 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010829 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010830 break;
Richard Smith998a5912011-06-05 22:42:48 +000010831 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010832
10833 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010834 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010835 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010836 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010837 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010838
Sam Panzer0f384432012-08-21 00:52:01 +000010839 case OR_Deleted: {
10840 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10841 << (*Best)->Function->isDeleted()
10842 << ULE->getName()
10843 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10844 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010845 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010846
Sam Panzer0f384432012-08-21 00:52:01 +000010847 // We emitted an error for the unvailable/deleted function call but keep
10848 // the call in the AST.
10849 FunctionDecl *FDecl = (*Best)->Function;
10850 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010851 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10852 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010853 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010854 }
10855
Douglas Gregorb412e172010-07-25 18:17:45 +000010856 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010857 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010858}
10859
Sam Panzer0f384432012-08-21 00:52:01 +000010860/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10861/// (which eventually refers to the declaration Func) and the call
10862/// arguments Args/NumArgs, attempt to resolve the function call down
10863/// to a specific function. If overload resolution succeeds, returns
10864/// the call expression produced by overload resolution.
10865/// Otherwise, emits diagnostics and returns ExprError.
10866ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10867 UnresolvedLookupExpr *ULE,
10868 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010869 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010870 SourceLocation RParenLoc,
10871 Expr *ExecConfig,
10872 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000010873 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10874 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000010875 ExprResult result;
10876
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010877 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10878 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010879 return result;
10880
10881 OverloadCandidateSet::iterator Best;
10882 OverloadingResult OverloadResult =
10883 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10884
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010885 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010886 RParenLoc, ExecConfig, &CandidateSet,
10887 &Best, OverloadResult,
10888 AllowTypoCorrection);
10889}
10890
John McCall4c4c1df2010-01-26 03:27:55 +000010891static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010892 return Functions.size() > 1 ||
10893 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10894}
10895
Douglas Gregor084d8552009-03-13 23:49:33 +000010896/// \brief Create a unary operation that may resolve to an overloaded
10897/// operator.
10898///
10899/// \param OpLoc The location of the operator itself (e.g., '*').
10900///
10901/// \param OpcIn The UnaryOperator::Opcode that describes this
10902/// operator.
10903///
James Dennett18348b62012-06-22 08:52:37 +000010904/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010905/// considered by overload resolution. The caller needs to build this
10906/// set based on the context using, e.g.,
10907/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10908/// set should not contain any member functions; those will be added
10909/// by CreateOverloadedUnaryOp().
10910///
James Dennett91738ff2012-06-22 10:32:46 +000010911/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010912ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010913Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10914 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010915 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010916 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010917
10918 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10919 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10920 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010921 // TODO: provide better source location info.
10922 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010923
John McCall4124c492011-10-17 18:40:02 +000010924 if (checkPlaceholderForOverload(*this, Input))
10925 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010926
Craig Topperc3ec1492014-05-26 06:22:03 +000010927 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000010928 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010929
Douglas Gregor084d8552009-03-13 23:49:33 +000010930 // For post-increment and post-decrement, add the implicit '0' as
10931 // the second argument, so that we know this is a post-increment or
10932 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010933 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010934 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010935 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10936 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010937 NumArgs = 2;
10938 }
10939
Richard Smithe54c3072013-05-05 15:51:06 +000010940 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10941
Douglas Gregor084d8552009-03-13 23:49:33 +000010942 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010943 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010944 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10945 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010946
Craig Topperc3ec1492014-05-26 06:22:03 +000010947 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010948 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010949 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010950 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010951 /*ADL*/ true, IsOverloaded(Fns),
10952 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010953 return new (Context)
10954 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10955 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010956 }
10957
10958 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000010959 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000010960
10961 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010962 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010963
10964 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010965 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010966
John McCall4c4c1df2010-01-26 03:27:55 +000010967 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000010968 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000010969 /*ExplicitTemplateArgs*/nullptr,
10970 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000010971
Douglas Gregor084d8552009-03-13 23:49:33 +000010972 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010973 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010974
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010975 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10976
Douglas Gregor084d8552009-03-13 23:49:33 +000010977 // Perform overload resolution.
10978 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010979 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010980 case OR_Success: {
10981 // We found a built-in operator or an overloaded operator.
10982 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010983
Douglas Gregor084d8552009-03-13 23:49:33 +000010984 if (FnDecl) {
10985 // We matched an overloaded operator. Build a call to that
10986 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010987
Douglas Gregor084d8552009-03-13 23:49:33 +000010988 // Convert the arguments.
10989 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010990 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010991
John Wiegley01296292011-04-08 18:41:53 +000010992 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000010993 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000010994 Best->FoundDecl, Method);
10995 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010996 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010997 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010998 } else {
10999 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011000 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011001 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011002 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011003 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011004 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011005 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011006 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011007 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011008 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011009 }
11010
Douglas Gregor084d8552009-03-13 23:49:33 +000011011 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011012 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011013 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011014 if (FnExpr.isInvalid())
11015 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011016
Richard Smithc1564702013-11-15 02:58:23 +000011017 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011018 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011019 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11020 ResultTy = ResultTy.getNonLValueExprType(Context);
11021
Eli Friedman030eee42009-11-18 03:58:17 +000011022 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011023 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011024 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011025 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011026
Alp Toker314cc812014-01-25 16:55:45 +000011027 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011028 return ExprError();
11029
John McCallb268a282010-08-23 23:25:46 +000011030 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011031 } else {
11032 // We matched a built-in operator. Convert the arguments, then
11033 // break out so that we will build the appropriate built-in
11034 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011035 ExprResult InputRes =
11036 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11037 Best->Conversions[0], AA_Passing);
11038 if (InputRes.isInvalid())
11039 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011040 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011041 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011042 }
John Wiegley01296292011-04-08 18:41:53 +000011043 }
11044
11045 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011046 // This is an erroneous use of an operator which can be overloaded by
11047 // a non-member function. Check for non-member operators which were
11048 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011049 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011050 // FIXME: Recover by calling the found function.
11051 return ExprError();
11052
John Wiegley01296292011-04-08 18:41:53 +000011053 // No viable function; fall through to handling this as a
11054 // built-in operator, which will produce an error message for us.
11055 break;
11056
11057 case OR_Ambiguous:
11058 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11059 << UnaryOperator::getOpcodeStr(Opc)
11060 << Input->getType()
11061 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011062 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011063 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11064 return ExprError();
11065
11066 case OR_Deleted:
11067 Diag(OpLoc, diag::err_ovl_deleted_oper)
11068 << Best->Function->isDeleted()
11069 << UnaryOperator::getOpcodeStr(Opc)
11070 << getDeletedOrUnavailableSuffix(Best->Function)
11071 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011072 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011073 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011074 return ExprError();
11075 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011076
11077 // Either we found no viable overloaded operator or we matched a
11078 // built-in operator. In either case, fall through to trying to
11079 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011080 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011081}
11082
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011083/// \brief Create a binary operation that may resolve to an overloaded
11084/// operator.
11085///
11086/// \param OpLoc The location of the operator itself (e.g., '+').
11087///
11088/// \param OpcIn The BinaryOperator::Opcode that describes this
11089/// operator.
11090///
James Dennett18348b62012-06-22 08:52:37 +000011091/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011092/// considered by overload resolution. The caller needs to build this
11093/// set based on the context using, e.g.,
11094/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11095/// set should not contain any member functions; those will be added
11096/// by CreateOverloadedBinOp().
11097///
11098/// \param LHS Left-hand argument.
11099/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011100ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011101Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000011102 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000011103 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011104 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011105 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011106 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011107
11108 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11109 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11110 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11111
11112 // If either side is type-dependent, create an appropriate dependent
11113 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011114 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011115 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011116 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011117 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011118 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011119 return new (Context) BinaryOperator(
11120 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11121 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011122
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011123 return new (Context) CompoundAssignOperator(
11124 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11125 Context.DependentTy, Context.DependentTy, OpLoc,
11126 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011127 }
John McCall4c4c1df2010-01-26 03:27:55 +000011128
11129 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011130 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011131 // TODO: provide better source location info in DNLoc component.
11132 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011133 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011134 = UnresolvedLookupExpr::Create(Context, NamingClass,
11135 NestedNameSpecifierLoc(), OpNameInfo,
11136 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011137 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011138 return new (Context)
11139 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11140 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011141 }
11142
John McCall4124c492011-10-17 18:40:02 +000011143 // Always do placeholder-like conversions on the RHS.
11144 if (checkPlaceholderForOverload(*this, Args[1]))
11145 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011146
John McCall526ab472011-10-25 17:37:35 +000011147 // Do placeholder-like conversion on the LHS; note that we should
11148 // not get here with a PseudoObject LHS.
11149 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011150 if (checkPlaceholderForOverload(*this, Args[0]))
11151 return ExprError();
11152
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011153 // If this is the assignment operator, we only perform overload resolution
11154 // if the left-hand side is a class or enumeration type. This is actually
11155 // a hack. The standard requires that we do overload resolution between the
11156 // various built-in candidates, but as DR507 points out, this can lead to
11157 // problems. So we do it this way, which pretty much follows what GCC does.
11158 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011159 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011160 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011161
John McCalle26a8722010-12-04 08:14:53 +000011162 // If this is the .* operator, which is not overloadable, just
11163 // create a built-in binary operator.
11164 if (Opc == BO_PtrMemD)
11165 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11166
Douglas Gregor084d8552009-03-13 23:49:33 +000011167 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011168 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011169
11170 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011171 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011172
11173 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011174 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011175
Richard Smith0daabd72014-09-23 20:31:39 +000011176 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11177 // performed for an assignment operator (nor for operator[] nor operator->,
11178 // which don't get here).
11179 if (Opc != BO_Assign)
11180 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11181 /*ExplicitTemplateArgs*/ nullptr,
11182 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011183
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011184 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011185 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011186
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011187 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11188
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011189 // Perform overload resolution.
11190 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011191 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011192 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011193 // We found a built-in operator or an overloaded operator.
11194 FunctionDecl *FnDecl = Best->Function;
11195
11196 if (FnDecl) {
11197 // We matched an overloaded operator. Build a call to that
11198 // operator.
11199
11200 // Convert the arguments.
11201 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011202 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011203 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011204
Chandler Carruth8e543b32010-12-12 08:17:55 +000011205 ExprResult Arg1 =
11206 PerformCopyInitialization(
11207 InitializedEntity::InitializeParameter(Context,
11208 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011209 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011210 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011211 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011212
John Wiegley01296292011-04-08 18:41:53 +000011213 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011214 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011215 Best->FoundDecl, Method);
11216 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011217 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011218 Args[0] = Arg0.getAs<Expr>();
11219 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011220 } else {
11221 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011222 ExprResult Arg0 = PerformCopyInitialization(
11223 InitializedEntity::InitializeParameter(Context,
11224 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011225 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011226 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011227 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011228
Chandler Carruth8e543b32010-12-12 08:17:55 +000011229 ExprResult Arg1 =
11230 PerformCopyInitialization(
11231 InitializedEntity::InitializeParameter(Context,
11232 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011233 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011234 if (Arg1.isInvalid())
11235 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011236 Args[0] = LHS = Arg0.getAs<Expr>();
11237 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011238 }
11239
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011240 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011241 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011242 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011243 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011244 if (FnExpr.isInvalid())
11245 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011246
Richard Smithc1564702013-11-15 02:58:23 +000011247 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011248 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011249 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11250 ResultTy = ResultTy.getNonLValueExprType(Context);
11251
John McCallb268a282010-08-23 23:25:46 +000011252 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011253 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011254 Args, ResultTy, VK, OpLoc,
11255 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011256
Alp Toker314cc812014-01-25 16:55:45 +000011257 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011258 FnDecl))
11259 return ExprError();
11260
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011261 ArrayRef<const Expr *> ArgsArray(Args, 2);
11262 // Cut off the implicit 'this'.
11263 if (isa<CXXMethodDecl>(FnDecl))
11264 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011265
11266 // Check for a self move.
11267 if (Op == OO_Equal)
11268 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11269
11270 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011271 TheCall->getSourceRange(), VariadicDoesNotApply);
11272
John McCallb268a282010-08-23 23:25:46 +000011273 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011274 } else {
11275 // We matched a built-in operator. Convert the arguments, then
11276 // break out so that we will build the appropriate built-in
11277 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011278 ExprResult ArgsRes0 =
11279 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11280 Best->Conversions[0], AA_Passing);
11281 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011282 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011283 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011284
John Wiegley01296292011-04-08 18:41:53 +000011285 ExprResult ArgsRes1 =
11286 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11287 Best->Conversions[1], AA_Passing);
11288 if (ArgsRes1.isInvalid())
11289 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011290 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011291 break;
11292 }
11293 }
11294
Douglas Gregor66950a32009-09-30 21:46:01 +000011295 case OR_No_Viable_Function: {
11296 // C++ [over.match.oper]p9:
11297 // If the operator is the operator , [...] and there are no
11298 // viable functions, then the operator is assumed to be the
11299 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011300 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011301 break;
11302
Chandler Carruth8e543b32010-12-12 08:17:55 +000011303 // For class as left operand for assignment or compound assigment
11304 // operator do not fall through to handling in built-in, but report that
11305 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011306 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011307 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011308 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011309 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11310 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011311 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011312 if (Args[0]->getType()->isIncompleteType()) {
11313 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11314 << Args[0]->getType()
11315 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11316 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011317 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011318 // This is an erroneous use of an operator which can be overloaded by
11319 // a non-member function. Check for non-member operators which were
11320 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011321 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011322 // FIXME: Recover by calling the found function.
11323 return ExprError();
11324
Douglas Gregor66950a32009-09-30 21:46:01 +000011325 // No viable function; try to create a built-in operation, which will
11326 // produce an error. Then, show the non-viable candidates.
11327 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011329 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011330 "C++ binary operator overloading is missing candidates!");
11331 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011332 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011333 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011334 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011335 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011336
11337 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011338 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011339 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011340 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011341 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011342 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011343 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011344 return ExprError();
11345
11346 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011347 if (isImplicitlyDeleted(Best->Function)) {
11348 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11349 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011350 << Context.getRecordType(Method->getParent())
11351 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011352
Richard Smithde1a4872012-12-28 12:23:24 +000011353 // The user probably meant to call this special member. Just
11354 // explain why it's deleted.
11355 NoteDeletedFunction(Method);
11356 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011357 } else {
11358 Diag(OpLoc, diag::err_ovl_deleted_oper)
11359 << Best->Function->isDeleted()
11360 << BinaryOperator::getOpcodeStr(Opc)
11361 << getDeletedOrUnavailableSuffix(Best->Function)
11362 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11363 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011364 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011365 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011366 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011367 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011368
Douglas Gregor66950a32009-09-30 21:46:01 +000011369 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011370 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011371}
11372
John McCalldadc5752010-08-24 06:29:42 +000011373ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011374Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11375 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011376 Expr *Base, Expr *Idx) {
11377 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011378 DeclarationName OpName =
11379 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11380
11381 // If either side is type-dependent, create an appropriate dependent
11382 // expression.
11383 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11384
Craig Topperc3ec1492014-05-26 06:22:03 +000011385 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011386 // CHECKME: no 'operator' keyword?
11387 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11388 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011389 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011390 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011391 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011392 /*ADL*/ true, /*Overloaded*/ false,
11393 UnresolvedSetIterator(),
11394 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011395 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011396
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011397 return new (Context)
11398 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11399 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011400 }
11401
John McCall4124c492011-10-17 18:40:02 +000011402 // Handle placeholders on both operands.
11403 if (checkPlaceholderForOverload(*this, Args[0]))
11404 return ExprError();
11405 if (checkPlaceholderForOverload(*this, Args[1]))
11406 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011407
Sebastian Redladba46e2009-10-29 20:17:01 +000011408 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011409 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011410
11411 // Subscript can only be overloaded as a member function.
11412
11413 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011414 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011415
11416 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011417 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011418
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011419 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11420
Sebastian Redladba46e2009-10-29 20:17:01 +000011421 // Perform overload resolution.
11422 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011423 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011424 case OR_Success: {
11425 // We found a built-in operator or an overloaded operator.
11426 FunctionDecl *FnDecl = Best->Function;
11427
11428 if (FnDecl) {
11429 // We matched an overloaded operator. Build a call to that
11430 // operator.
11431
John McCalla0296f72010-03-19 07:35:19 +000011432 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011433
Sebastian Redladba46e2009-10-29 20:17:01 +000011434 // Convert the arguments.
11435 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011436 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011437 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011438 Best->FoundDecl, Method);
11439 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011440 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011441 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011442
Anders Carlssona68e51e2010-01-29 18:37:50 +000011443 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011444 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011445 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011446 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011447 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011448 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011449 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011450 if (InputInit.isInvalid())
11451 return ExprError();
11452
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011453 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011454
Sebastian Redladba46e2009-10-29 20:17:01 +000011455 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011456 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11457 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011458 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011459 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011460 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011461 OpLocInfo.getLoc(),
11462 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011463 if (FnExpr.isInvalid())
11464 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011465
Richard Smithc1564702013-11-15 02:58:23 +000011466 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011467 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011468 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11469 ResultTy = ResultTy.getNonLValueExprType(Context);
11470
John McCallb268a282010-08-23 23:25:46 +000011471 CXXOperatorCallExpr *TheCall =
11472 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011473 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011474 ResultTy, VK, RLoc,
11475 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011476
Alp Toker314cc812014-01-25 16:55:45 +000011477 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011478 return ExprError();
11479
John McCallb268a282010-08-23 23:25:46 +000011480 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011481 } else {
11482 // We matched a built-in operator. Convert the arguments, then
11483 // break out so that we will build the appropriate built-in
11484 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011485 ExprResult ArgsRes0 =
11486 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11487 Best->Conversions[0], AA_Passing);
11488 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011489 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011490 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011491
11492 ExprResult ArgsRes1 =
11493 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11494 Best->Conversions[1], AA_Passing);
11495 if (ArgsRes1.isInvalid())
11496 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011497 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011498
11499 break;
11500 }
11501 }
11502
11503 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011504 if (CandidateSet.empty())
11505 Diag(LLoc, diag::err_ovl_no_oper)
11506 << Args[0]->getType() << /*subscript*/ 0
11507 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11508 else
11509 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11510 << Args[0]->getType()
11511 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011512 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011513 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011514 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011515 }
11516
11517 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011518 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011519 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011520 << Args[0]->getType() << Args[1]->getType()
11521 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011522 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011523 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011524 return ExprError();
11525
11526 case OR_Deleted:
11527 Diag(LLoc, diag::err_ovl_deleted_oper)
11528 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011529 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011530 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011531 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011532 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011533 return ExprError();
11534 }
11535
11536 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011537 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011538}
11539
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011540/// BuildCallToMemberFunction - Build a call to a member
11541/// function. MemExpr is the expression that refers to the member
11542/// function (and includes the object parameter), Args/NumArgs are the
11543/// arguments to the function call (not including the object
11544/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011545/// expression refers to a non-static member function or an overloaded
11546/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011547ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011548Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011549 SourceLocation LParenLoc,
11550 MultiExprArg Args,
11551 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011552 assert(MemExprE->getType() == Context.BoundMemberTy ||
11553 MemExprE->getType() == Context.OverloadTy);
11554
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011555 // Dig out the member expression. This holds both the object
11556 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011557 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011558
John McCall0009fcc2011-04-26 20:42:42 +000011559 // Determine whether this is a call to a pointer-to-member function.
11560 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11561 assert(op->getType() == Context.BoundMemberTy);
11562 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11563
11564 QualType fnType =
11565 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11566
11567 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11568 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011569 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011570
11571 // Check that the object type isn't more qualified than the
11572 // member function we're calling.
11573 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11574
11575 QualType objectType = op->getLHS()->getType();
11576 if (op->getOpcode() == BO_PtrMemI)
11577 objectType = objectType->castAs<PointerType>()->getPointeeType();
11578 Qualifiers objectQuals = objectType.getQualifiers();
11579
11580 Qualifiers difference = objectQuals - funcQuals;
11581 difference.removeObjCGCAttr();
11582 difference.removeAddressSpace();
11583 if (difference) {
11584 std::string qualsString = difference.getAsString();
11585 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11586 << fnType.getUnqualifiedType()
11587 << qualsString
11588 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11589 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011590
David Majnemerb3e56542014-08-07 22:56:13 +000011591 if (resultType->isMemberPointerType())
11592 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11593 RequireCompleteType(LParenLoc, resultType, 0);
11594
John McCall0009fcc2011-04-26 20:42:42 +000011595 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011596 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011597 resultType, valueKind, RParenLoc);
11598
Alp Toker314cc812014-01-25 16:55:45 +000011599 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011600 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011601 return ExprError();
11602
Craig Topperc3ec1492014-05-26 06:22:03 +000011603 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011604 return ExprError();
11605
Richard Trieu9be9c682013-06-22 02:30:38 +000011606 if (CheckOtherCall(call, proto))
11607 return ExprError();
11608
John McCall0009fcc2011-04-26 20:42:42 +000011609 return MaybeBindToTemporary(call);
11610 }
11611
John McCall4124c492011-10-17 18:40:02 +000011612 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011613 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011614 return ExprError();
11615
John McCall10eae182009-11-30 22:42:35 +000011616 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011617 CXXMethodDecl *Method = nullptr;
11618 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11619 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011620 if (isa<MemberExpr>(NakedMemExpr)) {
11621 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011622 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011623 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011624 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011625 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011626 } else {
11627 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011628 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011629
John McCall6e9f8f62009-12-03 04:06:58 +000011630 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011631 Expr::Classification ObjectClassification
11632 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11633 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011634
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011635 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011636 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11637 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011638
John McCall2d74de92009-12-01 22:10:20 +000011639 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011640 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011641 if (UnresExpr->hasExplicitTemplateArgs()) {
11642 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11643 TemplateArgs = &TemplateArgsBuffer;
11644 }
11645
John McCall10eae182009-11-30 22:42:35 +000011646 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11647 E = UnresExpr->decls_end(); I != E; ++I) {
11648
John McCall6e9f8f62009-12-03 04:06:58 +000011649 NamedDecl *Func = *I;
11650 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11651 if (isa<UsingShadowDecl>(Func))
11652 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11653
Douglas Gregor02824322011-01-26 19:30:28 +000011654
Francois Pichet64225792011-01-18 05:04:39 +000011655 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011656 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011657 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011658 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011659 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011660 // If explicit template arguments were provided, we can't call a
11661 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011662 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011663 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011664
John McCalla0296f72010-03-19 07:35:19 +000011665 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011666 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011667 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011668 } else {
John McCall10eae182009-11-30 22:42:35 +000011669 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011670 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011671 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011672 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011673 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011674 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011675 }
Mike Stump11289f42009-09-09 15:08:12 +000011676
John McCall10eae182009-11-30 22:42:35 +000011677 DeclarationName DeclName = UnresExpr->getMemberName();
11678
John McCall4124c492011-10-17 18:40:02 +000011679 UnbridgedCasts.restore();
11680
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011681 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011682 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011683 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011684 case OR_Success:
11685 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011686 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011687 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011688 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11689 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011690 // If FoundDecl is different from Method (such as if one is a template
11691 // and the other a specialization), make sure DiagnoseUseOfDecl is
11692 // called on both.
11693 // FIXME: This would be more comprehensively addressed by modifying
11694 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11695 // being used.
11696 if (Method != FoundDecl.getDecl() &&
11697 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11698 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011699 break;
11700
11701 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011702 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011703 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011704 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011705 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011706 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011707 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011708
11709 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011710 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011711 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011712 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011713 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011714 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011715
11716 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011717 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011718 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011719 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011720 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011721 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011722 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011723 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011724 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011725 }
11726
John McCall16df1e52010-03-30 21:47:33 +000011727 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011728
John McCall2d74de92009-12-01 22:10:20 +000011729 // If overload resolution picked a static member, build a
11730 // non-member call based on that function.
11731 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011732 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11733 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011734 }
11735
John McCall10eae182009-11-30 22:42:35 +000011736 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011737 }
11738
Alp Toker314cc812014-01-25 16:55:45 +000011739 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011740 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11741 ResultType = ResultType.getNonLValueExprType(Context);
11742
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011743 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011744 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011745 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011746 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011747
Eli Bendersky291a57e2014-09-25 23:59:08 +000011748 // (CUDA B.1): Check for invalid calls between targets.
11749 if (getLangOpts().CUDA) {
11750 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11751 if (CheckCUDATarget(Caller, Method)) {
11752 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11753 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11754 << IdentifyCUDATarget(Caller);
11755 return ExprError();
11756 }
11757 }
11758 }
11759
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011760 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000011761 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011762 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011763 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011764
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011765 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011766 // We only need to do this if there was actually an overload; otherwise
11767 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011768 if (!Method->isStatic()) {
11769 ExprResult ObjectArg =
11770 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11771 FoundDecl, Method);
11772 if (ObjectArg.isInvalid())
11773 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011774 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000011775 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011776
11777 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011778 const FunctionProtoType *Proto =
11779 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011780 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011781 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011782 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011783
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011784 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011785
Richard Smith55ce3522012-06-25 20:30:08 +000011786 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011787 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011788
Anders Carlsson47061ee2011-05-06 14:25:31 +000011789 if ((isa<CXXConstructorDecl>(CurContext) ||
11790 isa<CXXDestructorDecl>(CurContext)) &&
11791 TheCall->getMethodDecl()->isPure()) {
11792 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11793
Chandler Carruth59259262011-06-27 08:31:58 +000011794 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000011795 Diag(MemExpr->getLocStart(),
11796 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11797 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11798 << MD->getParent()->getDeclName();
11799
11800 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011801 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011802 }
John McCallb268a282010-08-23 23:25:46 +000011803 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011804}
11805
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011806/// BuildCallToObjectOfClassType - Build a call to an object of class
11807/// type (C++ [over.call.object]), which can end up invoking an
11808/// overloaded function call operator (@c operator()) or performing a
11809/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011810ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011811Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011812 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011813 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011814 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011815 if (checkPlaceholderForOverload(*this, Obj))
11816 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011817 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000011818
11819 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011820 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011821 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011822
Nico Weberb58e51c2014-11-19 05:21:39 +000011823 assert(Object.get()->getType()->isRecordType() &&
11824 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000011825 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011826
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011827 // C++ [over.call.object]p1:
11828 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011829 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011830 // candidate functions includes at least the function call
11831 // operators of T. The function call operators of T are obtained by
11832 // ordinary lookup of the name operator() in the context of
11833 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000011834 OverloadCandidateSet CandidateSet(LParenLoc,
11835 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000011836 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011837
John Wiegley01296292011-04-08 18:41:53 +000011838 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011839 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011840 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011841
John McCall27b18f82009-11-17 02:14:36 +000011842 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11843 LookupQualifiedName(R, Record->getDecl());
11844 R.suppressDiagnostics();
11845
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011846 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011847 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011848 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011849 Object.get()->Classify(Context),
11850 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011851 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011853
Douglas Gregorab7897a2008-11-19 22:57:39 +000011854 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011855 // In addition, for each (non-explicit in C++0x) conversion function
11856 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011857 //
11858 // operator conversion-type-id () cv-qualifier;
11859 //
11860 // where cv-qualifier is the same cv-qualification as, or a
11861 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011862 // denotes the type "pointer to function of (P1,...,Pn) returning
11863 // R", or the type "reference to pointer to function of
11864 // (P1,...,Pn) returning R", or the type "reference to function
11865 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011866 // is also considered as a candidate function. Similarly,
11867 // surrogate call functions are added to the set of candidate
11868 // functions for each conversion function declared in an
11869 // accessible base class provided the function is not hidden
11870 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011871 std::pair<CXXRecordDecl::conversion_iterator,
11872 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000011873 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011874 for (CXXRecordDecl::conversion_iterator
11875 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011876 NamedDecl *D = *I;
11877 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11878 if (isa<UsingShadowDecl>(D))
11879 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011880
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011881 // Skip over templated conversion functions; they aren't
11882 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011883 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011884 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011885
John McCall6e9f8f62009-12-03 04:06:58 +000011886 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011887 if (!Conv->isExplicit()) {
11888 // Strip the reference type (if any) and then the pointer type (if
11889 // any) to get down to what might be a function type.
11890 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11891 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11892 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011893
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011894 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11895 {
11896 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011897 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011898 }
11899 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011900 }
Mike Stump11289f42009-09-09 15:08:12 +000011901
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011902 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11903
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011904 // Perform overload resolution.
11905 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011906 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011907 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011908 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011909 // Overload resolution succeeded; we'll build the appropriate call
11910 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011911 break;
11912
11913 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011914 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011915 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011916 << Object.get()->getType() << /*call*/ 1
11917 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011918 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011919 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011920 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011921 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011922 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011923 break;
11924
11925 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011926 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011927 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011928 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011929 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011930 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011931
11932 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011933 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011934 diag::err_ovl_deleted_object_call)
11935 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011936 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011937 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011938 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011939 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011940 break;
Mike Stump11289f42009-09-09 15:08:12 +000011941 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011942
Douglas Gregorb412e172010-07-25 18:17:45 +000011943 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011944 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011945
John McCall4124c492011-10-17 18:40:02 +000011946 UnbridgedCasts.restore();
11947
Craig Topperc3ec1492014-05-26 06:22:03 +000011948 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000011949 // Since there is no function declaration, this is one of the
11950 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011951 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011952 = cast<CXXConversionDecl>(
11953 Best->Conversions[0].UserDefined.ConversionFunction);
11954
Craig Topperc3ec1492014-05-26 06:22:03 +000011955 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11956 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011957 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11958 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011959 assert(Conv == Best->FoundDecl.getDecl() &&
11960 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011961 // We selected one of the surrogate functions that converts the
11962 // object parameter to a function pointer. Perform the conversion
11963 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011964
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011965 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011966 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011967 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11968 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011969 if (Call.isInvalid())
11970 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011971 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011972 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11973 CK_UserDefinedConversion, Call.get(),
11974 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011975
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011976 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011977 }
11978
Craig Topperc3ec1492014-05-26 06:22:03 +000011979 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011980
Douglas Gregorab7897a2008-11-19 22:57:39 +000011981 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11982 // that calls this method, using Object for the implicit object
11983 // parameter and passing along the remaining arguments.
11984 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011985
11986 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011987 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011988 return ExprError();
11989
Chandler Carruth8e543b32010-12-12 08:17:55 +000011990 const FunctionProtoType *Proto =
11991 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011992
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011993 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000011994
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011995 DeclarationNameInfo OpLocInfo(
11996 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11997 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011998 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011999 HadMultipleCandidates,
12000 OpLocInfo.getLoc(),
12001 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012002 if (NewFn.isInvalid())
12003 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012004
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012005 // Build the full argument list for the method call (the implicit object
12006 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012007 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012008 MethodArgs[0] = Object.get();
12009 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12010
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012011 // Once we've built TheCall, all of the expressions are properly
12012 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012013 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012014 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12015 ResultTy = ResultTy.getNonLValueExprType(Context);
12016
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012017 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012018 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012019 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12020 ResultTy, VK, RParenLoc, false);
12021 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012022
Alp Toker314cc812014-01-25 16:55:45 +000012023 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012024 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012025
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012026 // We may have default arguments. If so, we need to allocate more
12027 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012028 if (Args.size() < NumParams)
12029 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012030
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012031 bool IsError = false;
12032
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012033 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012034 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012035 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012036 Best->FoundDecl, Method);
12037 if (ObjRes.isInvalid())
12038 IsError = true;
12039 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012040 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012041 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012042
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012043 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012044 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012045 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012046 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012047 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012048
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012049 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012050
John McCalldadc5752010-08-24 06:29:42 +000012051 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012052 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012053 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012054 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012055 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012056
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012057 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012058 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012059 } else {
John McCalldadc5752010-08-24 06:29:42 +000012060 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012061 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12062 if (DefArg.isInvalid()) {
12063 IsError = true;
12064 break;
12065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012066
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012067 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012068 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012069
12070 TheCall->setArg(i + 1, Arg);
12071 }
12072
12073 // If this is a variadic call, handle args passed through "...".
12074 if (Proto->isVariadic()) {
12075 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012076 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012077 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12078 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012079 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012080 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012081 }
12082 }
12083
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012084 if (IsError) return true;
12085
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012086 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012087
Richard Smith55ce3522012-06-25 20:30:08 +000012088 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012089 return true;
12090
John McCalle172be52010-08-24 06:09:16 +000012091 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012092}
12093
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012094/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012095/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012096/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012097ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012098Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12099 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012100 assert(Base->getType()->isRecordType() &&
12101 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012102
John McCall4124c492011-10-17 18:40:02 +000012103 if (checkPlaceholderForOverload(*this, Base))
12104 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012105
John McCallbc077cf2010-02-08 23:07:23 +000012106 SourceLocation Loc = Base->getExprLoc();
12107
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012108 // C++ [over.ref]p1:
12109 //
12110 // [...] An expression x->m is interpreted as (x.operator->())->m
12111 // for a class object x of type T if T::operator->() exists and if
12112 // the operator is selected as the best match function by the
12113 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012114 DeclarationName OpName =
12115 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012116 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012117 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012118
John McCallbc077cf2010-02-08 23:07:23 +000012119 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012120 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012121 return ExprError();
12122
John McCall27b18f82009-11-17 02:14:36 +000012123 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12124 LookupQualifiedName(R, BaseRecord->getDecl());
12125 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012126
12127 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012128 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012129 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012130 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012131 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012132
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012133 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12134
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012135 // Perform overload resolution.
12136 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012137 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012138 case OR_Success:
12139 // Overload resolution succeeded; we'll build the call below.
12140 break;
12141
12142 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012143 if (CandidateSet.empty()) {
12144 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012145 if (NoArrowOperatorFound) {
12146 // Report this specific error to the caller instead of emitting a
12147 // diagnostic, as requested.
12148 *NoArrowOperatorFound = true;
12149 return ExprError();
12150 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012151 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12152 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012153 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012154 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012155 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012156 }
12157 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012158 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012159 << "operator->" << 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 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012164 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12165 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012166 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012167 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012168
12169 case OR_Deleted:
12170 Diag(OpLoc, diag::err_ovl_deleted_oper)
12171 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012172 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012173 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012174 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012175 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012176 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012177 }
12178
Craig Topperc3ec1492014-05-26 06:22:03 +000012179 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012180
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012181 // Convert the object parameter.
12182 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012183 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012184 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012185 Best->FoundDecl, Method);
12186 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012187 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012188 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012189
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012190 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012191 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012192 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012193 if (FnExpr.isInvalid())
12194 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012195
Alp Toker314cc812014-01-25 16:55:45 +000012196 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012197 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12198 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012199 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012200 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012201 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012202
Alp Toker314cc812014-01-25 16:55:45 +000012203 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012204 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012205
12206 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012207}
12208
Richard Smithbcc22fc2012-03-09 08:00:36 +000012209/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12210/// a literal operator described by the provided lookup results.
12211ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12212 DeclarationNameInfo &SuffixInfo,
12213 ArrayRef<Expr*> Args,
12214 SourceLocation LitEndLoc,
12215 TemplateArgumentListInfo *TemplateArgs) {
12216 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012217
Richard Smith100b24a2014-04-17 01:52:14 +000012218 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12219 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012220 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12221 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012222
Richard Smithbcc22fc2012-03-09 08:00:36 +000012223 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12224
Richard Smithbcc22fc2012-03-09 08:00:36 +000012225 // Perform overload resolution. This will usually be trivial, but might need
12226 // to perform substitutions for a literal operator template.
12227 OverloadCandidateSet::iterator Best;
12228 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12229 case OR_Success:
12230 case OR_Deleted:
12231 break;
12232
12233 case OR_No_Viable_Function:
12234 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12235 << R.getLookupName();
12236 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12237 return ExprError();
12238
12239 case OR_Ambiguous:
12240 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12241 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12242 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012243 }
12244
Richard Smithbcc22fc2012-03-09 08:00:36 +000012245 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012246 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12247 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012248 SuffixInfo.getLoc(),
12249 SuffixInfo.getInfo());
12250 if (Fn.isInvalid())
12251 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012252
12253 // Check the argument types. This should almost always be a no-op, except
12254 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012255 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012256 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012257 ExprResult InputInit = PerformCopyInitialization(
12258 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12259 SourceLocation(), Args[ArgIdx]);
12260 if (InputInit.isInvalid())
12261 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012262 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012263 }
12264
Alp Toker314cc812014-01-25 16:55:45 +000012265 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012266 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12267 ResultTy = ResultTy.getNonLValueExprType(Context);
12268
Richard Smithc67fdd42012-03-07 08:35:16 +000012269 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012270 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012271 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012272 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12273
Alp Toker314cc812014-01-25 16:55:45 +000012274 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012275 return ExprError();
12276
Craig Topperc3ec1492014-05-26 06:22:03 +000012277 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012278 return ExprError();
12279
12280 return MaybeBindToTemporary(UDL);
12281}
12282
Sam Panzer0f384432012-08-21 00:52:01 +000012283/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12284/// given LookupResult is non-empty, it is assumed to describe a member which
12285/// will be invoked. Otherwise, the function will be found via argument
12286/// dependent lookup.
12287/// CallExpr is set to a valid expression and FRS_Success returned on success,
12288/// otherwise CallExpr is set to ExprError() and some non-success value
12289/// is returned.
12290Sema::ForRangeStatus
12291Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12292 SourceLocation RangeLoc, VarDecl *Decl,
12293 BeginEndFunction BEF,
12294 const DeclarationNameInfo &NameInfo,
12295 LookupResult &MemberLookup,
12296 OverloadCandidateSet *CandidateSet,
12297 Expr *Range, ExprResult *CallExpr) {
12298 CandidateSet->clear();
12299 if (!MemberLookup.empty()) {
12300 ExprResult MemberRef =
12301 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12302 /*IsPtr=*/false, CXXScopeSpec(),
12303 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012304 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012305 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +000012306 /*TemplateArgs=*/nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012307 if (MemberRef.isInvalid()) {
12308 *CallExpr = ExprError();
12309 Diag(Range->getLocStart(), diag::note_in_for_range)
12310 << RangeLoc << BEF << Range->getType();
12311 return FRS_DiagnosticIssued;
12312 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012313 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012314 if (CallExpr->isInvalid()) {
12315 *CallExpr = ExprError();
12316 Diag(Range->getLocStart(), diag::note_in_for_range)
12317 << RangeLoc << BEF << Range->getType();
12318 return FRS_DiagnosticIssued;
12319 }
12320 } else {
12321 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012322 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012323 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012324 NestedNameSpecifierLoc(), NameInfo,
12325 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012326 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012327
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012328 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012329 CandidateSet, CallExpr);
12330 if (CandidateSet->empty() || CandidateSetError) {
12331 *CallExpr = ExprError();
12332 return FRS_NoViableFunction;
12333 }
12334 OverloadCandidateSet::iterator Best;
12335 OverloadingResult OverloadResult =
12336 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12337
12338 if (OverloadResult == OR_No_Viable_Function) {
12339 *CallExpr = ExprError();
12340 return FRS_NoViableFunction;
12341 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012342 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012343 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012344 OverloadResult,
12345 /*AllowTypoCorrection=*/false);
12346 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12347 *CallExpr = ExprError();
12348 Diag(Range->getLocStart(), diag::note_in_for_range)
12349 << RangeLoc << BEF << Range->getType();
12350 return FRS_DiagnosticIssued;
12351 }
12352 }
12353 return FRS_Success;
12354}
12355
12356
Douglas Gregorcd695e52008-11-10 20:40:00 +000012357/// FixOverloadedFunctionReference - E is an expression that refers to
12358/// a C++ overloaded function (possibly with some parentheses and
12359/// perhaps a '&' around it). We have resolved the overloaded function
12360/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012361/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012362Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012363 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012364 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012365 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12366 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012367 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012368 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012369
Douglas Gregor51c538b2009-11-20 19:42:02 +000012370 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012371 }
12372
Douglas Gregor51c538b2009-11-20 19:42:02 +000012373 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012374 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12375 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012376 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012377 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012378 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012379 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012380 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012381 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012382
12383 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012384 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012385 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012386 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012387 }
12388
Douglas Gregor51c538b2009-11-20 19:42:02 +000012389 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012390 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012391 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012392 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12393 if (Method->isStatic()) {
12394 // Do nothing: static member functions aren't any different
12395 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012396 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012397 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012398 // UnresolvedLookupExpr holding an overloaded member function
12399 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012400 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12401 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012402 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012403 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012404
John McCalld14a8642009-11-21 08:51:07 +000012405 assert(isa<DeclRefExpr>(SubExpr)
12406 && "fixed to something other than a decl ref");
12407 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12408 && "fixed to a member ref with no nested name qualifier");
12409
12410 // We have taken the address of a pointer to member
12411 // function. Perform the computation here so that we get the
12412 // appropriate pointer to member type.
12413 QualType ClassType
12414 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12415 QualType MemPtrType
12416 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12417
John McCall7decc9e2010-11-18 06:31:45 +000012418 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12419 VK_RValue, OK_Ordinary,
12420 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012421 }
12422 }
John McCall16df1e52010-03-30 21:47:33 +000012423 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12424 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012425 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012426 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012427
John McCalle3027922010-08-25 11:45:40 +000012428 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012429 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012430 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012431 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012432 }
John McCalld14a8642009-11-21 08:51:07 +000012433
12434 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012435 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012436 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012437 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012438 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12439 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012440 }
12441
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012442 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12443 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012444 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012445 Fn,
John McCall113bee02012-03-10 09:33:50 +000012446 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012447 ULE->getNameLoc(),
12448 Fn->getType(),
12449 VK_LValue,
12450 Found.getDecl(),
12451 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012452 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012453 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12454 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012455 }
12456
John McCall10eae182009-11-30 22:42:35 +000012457 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012458 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012459 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012460 if (MemExpr->hasExplicitTemplateArgs()) {
12461 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12462 TemplateArgs = &TemplateArgsBuffer;
12463 }
John McCall6b51f282009-11-23 01:53:49 +000012464
John McCall2d74de92009-12-01 22:10:20 +000012465 Expr *Base;
12466
John McCall7decc9e2010-11-18 06:31:45 +000012467 // If we're filling in a static method where we used to have an
12468 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012469 if (MemExpr->isImplicitAccess()) {
12470 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012471 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12472 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012473 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012474 Fn,
John McCall113bee02012-03-10 09:33:50 +000012475 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012476 MemExpr->getMemberLoc(),
12477 Fn->getType(),
12478 VK_LValue,
12479 Found.getDecl(),
12480 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012481 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012482 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12483 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012484 } else {
12485 SourceLocation Loc = MemExpr->getMemberLoc();
12486 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012487 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012488 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012489 Base = new (Context) CXXThisExpr(Loc,
12490 MemExpr->getBaseType(),
12491 /*isImplicit=*/true);
12492 }
John McCall2d74de92009-12-01 22:10:20 +000012493 } else
John McCallc3007a22010-10-26 07:05:15 +000012494 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012495
John McCall4adb38c2011-04-27 00:36:17 +000012496 ExprValueKind valueKind;
12497 QualType type;
12498 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12499 valueKind = VK_LValue;
12500 type = Fn->getType();
12501 } else {
12502 valueKind = VK_RValue;
12503 type = Context.BoundMemberTy;
12504 }
12505
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012506 MemberExpr *ME = MemberExpr::Create(Context, Base,
12507 MemExpr->isArrow(),
12508 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012509 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012510 Fn,
12511 Found,
12512 MemExpr->getMemberNameInfo(),
12513 TemplateArgs,
12514 type, valueKind, OK_Ordinary);
12515 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000012516 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012517 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012518 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012519
John McCallc3007a22010-10-26 07:05:15 +000012520 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012521}
12522
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012523ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012524 DeclAccessPair Found,
12525 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012526 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012527}