blob: 664b6a48482a8bbbfd27060c88ca0d0e807663ea [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035#include <algorithm>
David Blaikie8ad22e62014-05-01 23:01:41 +000036#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000037
Richard Smith17c00b42014-11-12 01:24:00 +000038using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000039using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000040
Nick Lewycky134af912013-02-07 05:08:22 +000041/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000042static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000043CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000045 SourceLocation Loc = SourceLocation(),
46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000047 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000048 return ExprError();
49 // If FoundDecl is different from Fn (such as if one is a template
50 // and the other a specialization), make sure DiagnoseUseOfDecl is
51 // called on both.
52 // FIXME: This would be more comprehensively addressed by modifying
53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
54 // being used.
55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000056 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000057 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000058 VK_LValue, Loc, LocInfo);
59 if (HadMultipleCandidates)
60 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000061
62 S.MarkDeclRefReferenced(DRE);
Nick Lewycky134af912013-02-07 05:08:22 +000063
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000064 ExprResult E = DRE;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000065 E = S.DefaultFunctionArrayConversion(E.get());
John Wiegley01296292011-04-08 18:41:53 +000066 if (E.isInvalid())
67 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000068 return E;
John McCall7decc9e2010-11-18 06:31:45 +000069}
70
John McCall5c32be02010-08-24 20:38:10 +000071static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000073 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000074 bool CStyle,
75 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000076
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000077static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
78 QualType &ToType,
79 bool InOverloadResolution,
80 StandardConversionSequence &SCS,
81 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000082static OverloadingResult
83IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84 UserDefinedConversionSequence& User,
85 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000086 bool AllowExplicit,
87 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000088
89
90static ImplicitConversionSequence::CompareKind
91CompareStandardConversionSequences(Sema &S,
92 const StandardConversionSequence& SCS1,
93 const StandardConversionSequence& SCS2);
94
95static ImplicitConversionSequence::CompareKind
96CompareQualificationConversions(Sema &S,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareDerivedToBaseConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105/// GetConversionRank - Retrieve the implicit conversion rank
106/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000107ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 static const ImplicitConversionRank
109 Rank[(int)ICK_Num_Conversion_Kinds] = {
110 ICR_Exact_Match,
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000115 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICR_Promotion,
117 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000118 ICR_Promotion,
119 ICR_Conversion,
120 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000126 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000127 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000128 ICR_Conversion,
129 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000130 ICR_Complex_Real_Conversion,
131 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000132 ICR_Conversion,
133 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134 };
135 return Rank[(int)Kind];
136}
137
138/// GetImplicitConversionName - Return the name of this kind of
139/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000140static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000141 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000142 "No conversion",
143 "Lvalue-to-rvalue",
144 "Array-to-pointer",
145 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000146 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 "Qualification",
148 "Integral promotion",
149 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000150 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 "Integral conversion",
152 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000153 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000154 "Floating-integral conversion",
155 "Pointer conversion",
156 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000157 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000158 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000159 "Derived-to-base conversion",
160 "Vector conversion",
161 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000162 "Complex-real conversion",
163 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000164 "Transparent Union Conversion",
John McCall31168b02011-06-15 23:02:42 +0000165 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000166 };
167 return Name[Kind];
168}
169
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000170/// StandardConversionSequence - Set the standard conversion
171/// sequence to the identity conversion.
172void StandardConversionSequence::setAsIdentityConversion() {
173 First = ICK_Identity;
174 Second = ICK_Identity;
175 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000176 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000177 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000178 ReferenceBinding = false;
179 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000180 IsLvalueReference = true;
181 BindsToFunctionLvalue = false;
182 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000183 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000184 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000186}
187
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000188/// getRank - Retrieve the rank of this standard conversion sequence
189/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
190/// implicit conversions.
191ImplicitConversionRank StandardConversionSequence::getRank() const {
192 ImplicitConversionRank Rank = ICR_Exact_Match;
193 if (GetConversionRank(First) > Rank)
194 Rank = GetConversionRank(First);
195 if (GetConversionRank(Second) > Rank)
196 Rank = GetConversionRank(Second);
197 if (GetConversionRank(Third) > Rank)
198 Rank = GetConversionRank(Third);
199 return Rank;
200}
201
202/// isPointerConversionToBool - Determines whether this conversion is
203/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000204/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000206bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000207 // Note that FromType has not necessarily been transformed by the
208 // array-to-pointer or function-to-pointer implicit conversions, so
209 // check for their presence as well as checking whether FromType is
210 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000211 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000212 (getFromType()->isPointerType() ||
213 getFromType()->isObjCObjectPointerType() ||
214 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000215 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000216 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
217 return true;
218
219 return false;
220}
221
Douglas Gregor5c407d92008-10-23 00:40:37 +0000222/// isPointerConversionToVoidPointer - Determines whether this
223/// conversion is a conversion of a pointer to a void pointer. This is
224/// used as part of the ranking of standard conversion sequences (C++
225/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000226bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000227StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000228isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000229 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000230 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000231
232 // Note that FromType has not necessarily been transformed by the
233 // array-to-pointer implicit conversion, so check for its presence
234 // and redo the conversion to get a pointer.
235 if (First == ICK_Array_To_Pointer)
236 FromType = Context.getArrayDecayedType(FromType);
237
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000238 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000239 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240 return ToPtrType->getPointeeType()->isVoidType();
241
242 return false;
243}
244
Richard Smith66e05fe2012-01-18 05:21:49 +0000245/// Skip any implicit casts which could be either part of a narrowing conversion
246/// or after one in an implicit conversion.
247static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
248 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
249 switch (ICE->getCastKind()) {
250 case CK_NoOp:
251 case CK_IntegralCast:
252 case CK_IntegralToBoolean:
253 case CK_IntegralToFloating:
254 case CK_FloatingToIntegral:
255 case CK_FloatingToBoolean:
256 case CK_FloatingCast:
257 Converted = ICE->getSubExpr();
258 continue;
259
260 default:
261 return Converted;
262 }
263 }
264
265 return Converted;
266}
267
268/// Check if this standard conversion sequence represents a narrowing
269/// conversion, according to C++11 [dcl.init.list]p7.
270///
271/// \param Ctx The AST context.
272/// \param Converted The result of applying this standard conversion sequence.
273/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
274/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000275/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
276/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000277NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000278StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
279 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000280 APValue &ConstantValue,
281 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000282 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000283
284 // C++11 [dcl.init.list]p7:
285 // A narrowing conversion is an implicit conversion ...
286 QualType FromType = getToType(0);
287 QualType ToType = getToType(1);
288 switch (Second) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000289 // 'bool' is an integral type; dispatch to the right place to handle it.
290 case ICK_Boolean_Conversion:
291 if (FromType->isRealFloatingType())
292 goto FloatingIntegralConversion;
293 if (FromType->isIntegralOrUnscopedEnumerationType())
294 goto IntegralConversion;
295 // Boolean conversions can be from pointers and pointers to members
296 // [conv.bool], and those aren't considered narrowing conversions.
297 return NK_Not_Narrowing;
298
Richard Smith66e05fe2012-01-18 05:21:49 +0000299 // -- from a floating-point type to an integer type, or
300 //
301 // -- from an integer type or unscoped enumeration type to a floating-point
302 // type, except where the source is a constant expression and the actual
303 // value after conversion will fit into the target type and will produce
304 // the original value when converted back to the original type, or
305 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000306 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000307 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
308 return NK_Type_Narrowing;
309 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
310 llvm::APSInt IntConstantValue;
311 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
312 if (Initializer &&
313 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
314 // Convert the integer to the floating type.
315 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
316 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
317 llvm::APFloat::rmNearestTiesToEven);
318 // And back.
319 llvm::APSInt ConvertedValue = IntConstantValue;
320 bool ignored;
321 Result.convertToInteger(ConvertedValue,
322 llvm::APFloat::rmTowardZero, &ignored);
323 // If the resulting value is different, this was a narrowing conversion.
324 if (IntConstantValue != ConvertedValue) {
325 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000326 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000327 return NK_Constant_Narrowing;
328 }
329 } else {
330 // Variables are always narrowings.
331 return NK_Variable_Narrowing;
332 }
333 }
334 return NK_Not_Narrowing;
335
336 // -- from long double to double or float, or from double to float, except
337 // where the source is a constant expression and the actual value after
338 // conversion is within the range of values that can be represented (even
339 // if it cannot be represented exactly), or
340 case ICK_Floating_Conversion:
341 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
342 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
343 // FromType is larger than ToType.
344 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
345 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
346 // Constant!
347 assert(ConstantValue.isFloat());
348 llvm::APFloat FloatVal = ConstantValue.getFloat();
349 // Convert the source value into the target type.
350 bool ignored;
351 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
352 Ctx.getFloatTypeSemantics(ToType),
353 llvm::APFloat::rmNearestTiesToEven, &ignored);
354 // If there was no overflow, the source value is within the range of
355 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000356 if (ConvertStatus & llvm::APFloat::opOverflow) {
357 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000358 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000359 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000360 } else {
361 return NK_Variable_Narrowing;
362 }
363 }
364 return NK_Not_Narrowing;
365
366 // -- from an integer type or unscoped enumeration type to an integer type
367 // that cannot represent all the values of the original type, except where
368 // the source is a constant expression and the actual value after
369 // conversion will fit into the target type and will produce the original
370 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000371 case ICK_Integral_Conversion:
372 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000373 assert(FromType->isIntegralOrUnscopedEnumerationType());
374 assert(ToType->isIntegralOrUnscopedEnumerationType());
375 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
376 const unsigned FromWidth = Ctx.getIntWidth(FromType);
377 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
378 const unsigned ToWidth = Ctx.getIntWidth(ToType);
379
380 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000381 (FromWidth == ToWidth && FromSigned != ToSigned) ||
382 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000383 // Not all values of FromType can be represented in ToType.
384 llvm::APSInt InitializerValue;
385 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000386 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
387 // Such conversions on variables are always narrowing.
388 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000389 }
390 bool Narrowing = false;
391 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000392 // Negative -> unsigned is narrowing. Otherwise, more bits is never
393 // narrowing.
394 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000395 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000396 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000397 // Add a bit to the InitializerValue so we don't have to worry about
398 // signed vs. unsigned comparisons.
399 InitializerValue = InitializerValue.extend(
400 InitializerValue.getBitWidth() + 1);
401 // Convert the initializer to and from the target width and signed-ness.
402 llvm::APSInt ConvertedValue = InitializerValue;
403 ConvertedValue = ConvertedValue.trunc(ToWidth);
404 ConvertedValue.setIsSigned(ToSigned);
405 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
406 ConvertedValue.setIsSigned(InitializerValue.isSigned());
407 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000408 if (ConvertedValue != InitializerValue)
409 Narrowing = true;
410 }
411 if (Narrowing) {
412 ConstantType = Initializer->getType();
413 ConstantValue = APValue(InitializerValue);
414 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000415 }
416 }
417 return NK_Not_Narrowing;
418 }
419
420 default:
421 // Other kinds of conversions are not narrowings.
422 return NK_Not_Narrowing;
423 }
424}
425
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000426/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000427/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000428void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000429 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000430 bool PrintedSomething = false;
431 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000432 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000433 PrintedSomething = true;
434 }
435
436 if (Second != ICK_Identity) {
437 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000438 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000439 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000440 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000441
442 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000443 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000444 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000445 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000446 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000447 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000448 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000449 PrintedSomething = true;
450 }
451
452 if (Third != ICK_Identity) {
453 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000454 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000455 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000456 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 PrintedSomething = true;
458 }
459
460 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000461 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000462 }
463}
464
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000465/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000467void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000468 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000470 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000471 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000472 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000473 if (ConversionFunction)
474 OS << '\'' << *ConversionFunction << '\'';
475 else
476 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000478 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000479 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 }
481}
482
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000483/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000485void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000486 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000487 if (isStdInitializerListElement())
488 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 switch (ConversionKind) {
490 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000491 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000492 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493 break;
494 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000495 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000496 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 break;
498 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 break;
John McCall0d1da222010-01-12 00:44:57 +0000501 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000502 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000503 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 break;
507 }
508
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000509 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510}
511
John McCall0d1da222010-01-12 00:44:57 +0000512void AmbiguousConversionSequence::construct() {
513 new (&conversions()) ConversionSet();
514}
515
516void AmbiguousConversionSequence::destruct() {
517 conversions().~ConversionSet();
518}
519
520void
521AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
522 FromTypePtr = O.FromTypePtr;
523 ToTypePtr = O.ToTypePtr;
524 new (&conversions()) ConversionSet(O.conversions());
525}
526
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000527namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000528 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000529 // template argument information.
530 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000531 TemplateArgument FirstArg;
532 TemplateArgument SecondArg;
533 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000534 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000535 // template parameter and template argument information.
536 struct DFIParamWithArguments : DFIArguments {
537 TemplateParameter Param;
538 };
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000539}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000540
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000541/// \brief Convert from Sema's representation of template deduction information
542/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000543DeductionFailureInfo
544clang::MakeDeductionFailureInfo(ASTContext &Context,
545 Sema::TemplateDeductionResult TDK,
546 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000547 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000548 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000549 Result.HasDiagnostic = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000550 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000551 switch (TDK) {
552 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000553 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000554 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000555 case Sema::TDK_TooManyArguments:
556 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000557 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000559 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000560 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000561 Result.Data = Info.Param.getOpaqueValue();
562 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
Richard Smith44ecdbd2013-01-31 05:19:49 +0000564 case Sema::TDK_NonDeducedMismatch: {
565 // FIXME: Should allocate from normal heap so that we can free this later.
566 DFIArguments *Saved = new (Context) DFIArguments;
567 Saved->FirstArg = Info.FirstArg;
568 Saved->SecondArg = Info.SecondArg;
569 Result.Data = Saved;
570 break;
571 }
572
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000573 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000574 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000575 // FIXME: Should allocate from normal heap so that we can free this later.
576 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000577 Saved->Param = Info.Param;
578 Saved->FirstArg = Info.FirstArg;
579 Saved->SecondArg = Info.SecondArg;
580 Result.Data = Saved;
581 break;
582 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000584 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000585 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000586 if (Info.hasSFINAEDiagnostic()) {
587 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
588 SourceLocation(), PartialDiagnostic::NullDiagnostic());
589 Info.takeSFINAEDiagnostic(*Diag);
590 Result.HasDiagnostic = true;
591 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000592 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000595 Result.Data = Info.Expression;
596 break;
597
Richard Smith44ecdbd2013-01-31 05:19:49 +0000598 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 return Result;
603}
John McCall0d1da222010-01-12 00:44:57 +0000604
Larisse Voufo98b20f12013-07-19 23:00:19 +0000605void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000606 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
607 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000608 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 case Sema::TDK_InstantiationDepth:
610 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000611 case Sema::TDK_TooManyArguments:
612 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000613 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000614 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000617 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000618 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000619 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000620 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000621 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000622 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000623
624 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000625 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000626 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000627 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
628 Diag->~PartialDiagnosticAt();
629 HasDiagnostic = false;
630 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000631 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632
Douglas Gregor461761d2010-05-08 18:20:53 +0000633 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000634 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000635 break;
636 }
637}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Larisse Voufo98b20f12013-07-19 23:00:19 +0000639PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000640 if (HasDiagnostic)
641 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000642 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000643}
644
Larisse Voufo98b20f12013-07-19 23:00:19 +0000645TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000646 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
647 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000648 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000649 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000650 case Sema::TDK_TooManyArguments:
651 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000652 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000653 case Sema::TDK_NonDeducedMismatch:
654 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000655 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000657 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000658 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660
661 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000662 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000663 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000665 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000666 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000667 break;
668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000670 return TemplateParameter();
671}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672
Larisse Voufo98b20f12013-07-19 23:00:19 +0000673TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000674 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000675 case Sema::TDK_Success:
676 case Sema::TDK_Invalid:
677 case Sema::TDK_InstantiationDepth:
678 case Sema::TDK_TooManyArguments:
679 case Sema::TDK_TooFewArguments:
680 case Sema::TDK_Incomplete:
681 case Sema::TDK_InvalidExplicitArguments:
682 case Sema::TDK_Inconsistent:
683 case Sema::TDK_Underqualified:
684 case Sema::TDK_NonDeducedMismatch:
685 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000686 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000687
Richard Smith44ecdbd2013-01-31 05:19:49 +0000688 case Sema::TDK_SubstitutionFailure:
689 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000690
Richard Smith44ecdbd2013-01-31 05:19:49 +0000691 // Unhandled
692 case Sema::TDK_MiscellaneousDeductionFailure:
693 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000694 }
695
Craig Topperc3ec1492014-05-26 06:22:03 +0000696 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000697}
698
Larisse Voufo98b20f12013-07-19 23:00:19 +0000699const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
701 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000702 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000707 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000708 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000709 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000710 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000711
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000712 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000713 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000714 case Sema::TDK_NonDeducedMismatch:
715 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000716
Douglas Gregor461761d2010-05-08 18:20:53 +0000717 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000718 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000719 break;
720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721
Craig Topperc3ec1492014-05-26 06:22:03 +0000722 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000724
Larisse Voufo98b20f12013-07-19 23:00:19 +0000725const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000728 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000733 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000734 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000735 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000736 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000737
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000739 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000742
Douglas Gregor461761d2010-05-08 18:20:53 +0000743 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000744 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000745 break;
746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000747
Craig Topperc3ec1492014-05-26 06:22:03 +0000748 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000749}
750
Larisse Voufo98b20f12013-07-19 23:00:19 +0000751Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000752 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
753 Sema::TDK_FailedOverloadResolution)
754 return static_cast<Expr*>(Data);
755
Craig Topperc3ec1492014-05-26 06:22:03 +0000756 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000757}
758
Benjamin Kramer97e59492012-10-09 15:52:25 +0000759void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000760 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000761 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
762 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000763 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
764 i->DeductionFailure.Destroy();
765 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000766}
767
768void OverloadCandidateSet::clear() {
769 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000770 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000771 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000772 Functions.clear();
773}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774
John McCall4124c492011-10-17 18:40:02 +0000775namespace {
776 class UnbridgedCastsSet {
777 struct Entry {
778 Expr **Addr;
779 Expr *Saved;
780 };
781 SmallVector<Entry, 2> Entries;
782
783 public:
784 void save(Sema &S, Expr *&E) {
785 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
786 Entry entry = { &E, E };
787 Entries.push_back(entry);
788 E = S.stripARCUnbridgedCast(E);
789 }
790
791 void restore() {
792 for (SmallVectorImpl<Entry>::iterator
793 i = Entries.begin(), e = Entries.end(); i != e; ++i)
794 *i->Addr = i->Saved;
795 }
796 };
797}
798
799/// checkPlaceholderForOverload - Do any interesting placeholder-like
800/// preprocessing on the given expression.
801///
802/// \param unbridgedCasts a collection to which to add unbridged casts;
803/// without this, they will be immediately diagnosed as errors
804///
805/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000806static bool
807checkPlaceholderForOverload(Sema &S, Expr *&E,
808 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000809 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
810 // We can't handle overloaded expressions here because overload
811 // resolution might reasonably tweak them.
812 if (placeholder->getKind() == BuiltinType::Overload) return false;
813
814 // If the context potentially accepts unbridged ARC casts, strip
815 // the unbridged cast and add it to the collection for later restoration.
816 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
817 unbridgedCasts) {
818 unbridgedCasts->save(S, E);
819 return false;
820 }
821
822 // Go ahead and check everything else.
823 ExprResult result = S.CheckPlaceholderExpr(E);
824 if (result.isInvalid())
825 return true;
826
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000827 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000828 return false;
829 }
830
831 // Nothing to do.
832 return false;
833}
834
835/// checkArgPlaceholdersForOverload - Check a set of call operands for
836/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000837static bool checkArgPlaceholdersForOverload(Sema &S,
838 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000839 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000840 for (unsigned i = 0, e = Args.size(); i != e; ++i)
841 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000842 return true;
843
844 return false;
845}
846
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000847// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000848// overload of the declarations in Old. This routine returns false if
849// New and Old cannot be overloaded, e.g., if New has the same
850// signature as some function in Old (C++ 1.3.10) or if the Old
851// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000852// it does return false, MatchedDecl will point to the decl that New
853// cannot be overloaded with. This decl may be a UsingShadowDecl on
854// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000855//
856// Example: Given the following input:
857//
858// void f(int, float); // #1
859// void f(int, int); // #2
860// int f(int, int); // #3
861//
862// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000863// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000864//
John McCall3d988d92009-12-02 08:47:38 +0000865// When we process #2, Old contains only the FunctionDecl for #1. By
866// comparing the parameter types, we see that #1 and #2 are overloaded
867// (since they have different signatures), so this routine returns
868// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000869//
John McCall3d988d92009-12-02 08:47:38 +0000870// When we process #3, Old is an overload set containing #1 and #2. We
871// compare the signatures of #3 to #1 (they're overloaded, so we do
872// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
873// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000874// signature), IsOverload returns false and MatchedDecl will be set to
875// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000876//
877// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
878// into a class by a using declaration. The rules for whether to hide
879// shadow declarations ignore some properties which otherwise figure
880// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000881Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000882Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
883 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000884 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000885 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000886 NamedDecl *OldD = *I;
887
888 bool OldIsUsingDecl = false;
889 if (isa<UsingShadowDecl>(OldD)) {
890 OldIsUsingDecl = true;
891
892 // We can always introduce two using declarations into the same
893 // context, even if they have identical signatures.
894 if (NewIsUsingDecl) continue;
895
896 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
897 }
898
899 // If either declaration was introduced by a using declaration,
900 // we'll need to use slightly different rules for matching.
901 // Essentially, these rules are the normal rules, except that
902 // function templates hide function templates with different
903 // return types or template parameter lists.
904 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000905 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
906 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000907
Alp Tokera2794f92014-01-22 07:29:52 +0000908 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000909 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
910 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
911 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
912 continue;
913 }
914
Alp Tokera2794f92014-01-22 07:29:52 +0000915 if (!isa<FunctionTemplateDecl>(OldD) &&
916 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000917 continue;
918
John McCalldaa3d6b2009-12-09 03:35:25 +0000919 Match = *I;
920 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000921 }
John McCalla8987a2942010-11-10 03:01:53 +0000922 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000923 // We can overload with these, which can show up when doing
924 // redeclaration checks for UsingDecls.
925 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000926 } else if (isa<TagDecl>(OldD)) {
927 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000928 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
929 // Optimistically assume that an unresolved using decl will
930 // overload; if it doesn't, we'll have to diagnose during
931 // template instantiation.
932 } else {
John McCall1f82f242009-11-18 22:49:29 +0000933 // (C++ 13p1):
934 // Only function declarations can be overloaded; object and type
935 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000936 Match = *I;
937 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000938 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000939 }
John McCall1f82f242009-11-18 22:49:29 +0000940
John McCalldaa3d6b2009-12-09 03:35:25 +0000941 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000942}
943
Richard Smithac974a32013-06-30 09:48:50 +0000944bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
945 bool UseUsingDeclRules) {
946 // C++ [basic.start.main]p2: This function shall not be overloaded.
947 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000948 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000949
David Majnemerc729b0b2013-09-16 22:44:20 +0000950 // MSVCRT user defined entry points cannot be overloaded.
951 if (New->isMSVCRTEntryPoint())
952 return false;
953
John McCall1f82f242009-11-18 22:49:29 +0000954 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
955 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
956
957 // C++ [temp.fct]p2:
958 // A function template can be overloaded with other function templates
959 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +0000960 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +0000961 return true;
962
963 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000964 QualType OldQType = Context.getCanonicalType(Old->getType());
965 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000966
967 // Compare the signatures (C++ 1.3.10) of the two functions to
968 // determine whether they are overloads. If we find any mismatch
969 // in the signature, they are overloads.
970
971 // If either of these functions is a K&R-style function (no
972 // prototype), then we consider them to have matching signatures.
973 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
974 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
975 return false;
976
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000977 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
978 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000979
980 // The signature of a function includes the types of its
981 // parameters (C++ 1.3.10), which includes the presence or absence
982 // of the ellipsis; see C++ DR 357).
983 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +0000984 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +0000985 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000986 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000987 return true;
988
989 // C++ [temp.over.link]p4:
990 // The signature of a function template consists of its function
991 // signature, its return type and its template parameter list. The names
992 // of the template parameters are significant only for establishing the
993 // relationship between the template parameters and the rest of the
994 // signature.
995 //
996 // We check the return type and template parameter lists for function
997 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000998 //
999 // However, we don't consider either of these when deciding whether
1000 // a member introduced by a shadow declaration is hidden.
1001 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001002 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1003 OldTemplate->getTemplateParameters(),
1004 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001005 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001006 return true;
1007
1008 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001009 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001010 //
1011 // As part of this, also check whether one of the member functions
1012 // is static, in which case they are not overloads (C++
1013 // 13.1p2). While not part of the definition of the signature,
1014 // this check is important to determine whether these functions
1015 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001016 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1017 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001018 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001019 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1020 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1021 if (!UseUsingDeclRules &&
1022 (OldMethod->getRefQualifier() == RQ_None ||
1023 NewMethod->getRefQualifier() == RQ_None)) {
1024 // C++0x [over.load]p2:
1025 // - Member function declarations with the same name and the same
1026 // parameter-type-list as well as member function template
1027 // declarations with the same name, the same parameter-type-list, and
1028 // the same template parameter lists cannot be overloaded if any of
1029 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001030 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001031 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001032 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001033 }
1034 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001035 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036
Richard Smith574f4f62013-01-14 05:37:29 +00001037 // We may not have applied the implicit const for a constexpr member
1038 // function yet (because we haven't yet resolved whether this is a static
1039 // or non-static member function). Add it now, on the assumption that this
1040 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001041 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001042 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001043 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001044 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001045 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001046
1047 // We do not allow overloading based off of '__restrict'.
1048 OldQuals &= ~Qualifiers::Restrict;
1049 NewQuals &= ~Qualifiers::Restrict;
1050 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001051 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001052 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001053
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001054 // enable_if attributes are an order-sensitive part of the signature.
1055 for (specific_attr_iterator<EnableIfAttr>
1056 NewI = New->specific_attr_begin<EnableIfAttr>(),
1057 NewE = New->specific_attr_end<EnableIfAttr>(),
1058 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1059 OldE = Old->specific_attr_end<EnableIfAttr>();
1060 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1061 if (NewI == NewE || OldI == OldE)
1062 return true;
1063 llvm::FoldingSetNodeID NewID, OldID;
1064 NewI->getCond()->Profile(NewID, Context, true);
1065 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001066 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001067 return true;
1068 }
1069
John McCall1f82f242009-11-18 22:49:29 +00001070 // The signatures match; this is not an overload.
1071 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001072}
1073
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001074/// \brief Checks availability of the function depending on the current
1075/// function context. Inside an unavailable function, unavailability is ignored.
1076///
1077/// \returns true if \arg FD is unavailable and current context is inside
1078/// an available function, false otherwise.
1079bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1080 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1081}
1082
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001083/// \brief Tries a user-defined conversion from From to ToType.
1084///
1085/// Produces an implicit conversion sequence for when a standard conversion
1086/// is not an option. See TryImplicitConversion for more information.
1087static ImplicitConversionSequence
1088TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1089 bool SuppressUserConversions,
1090 bool AllowExplicit,
1091 bool InOverloadResolution,
1092 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001093 bool AllowObjCWritebackConversion,
1094 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001095 ImplicitConversionSequence ICS;
1096
1097 if (SuppressUserConversions) {
1098 // We're not in the case above, so there is no conversion that
1099 // we can perform.
1100 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1101 return ICS;
1102 }
1103
1104 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001105 OverloadCandidateSet Conversions(From->getExprLoc(),
1106 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001107 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1108 Conversions, AllowExplicit,
1109 AllowObjCConversionOnExplicit)) {
1110 case OR_Success:
1111 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001112 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001113 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001114 // C++ [over.ics.user]p4:
1115 // A conversion of an expression of class type to the same class
1116 // type is given Exact Match rank, and a conversion of an
1117 // expression of class type to a base class of that type is
1118 // given Conversion rank, in spite of the fact that a copy
1119 // constructor (i.e., a user-defined conversion function) is
1120 // called for those cases.
1121 if (CXXConstructorDecl *Constructor
1122 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1123 QualType FromCanon
1124 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1125 QualType ToCanon
1126 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1127 if (Constructor->isCopyConstructor() &&
1128 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1129 // Turn this into a "standard" conversion sequence, so that it
1130 // gets ranked with standard conversion sequences.
1131 ICS.setStandard();
1132 ICS.Standard.setAsIdentityConversion();
1133 ICS.Standard.setFromType(From->getType());
1134 ICS.Standard.setAllToTypes(ToType);
1135 ICS.Standard.CopyConstructor = Constructor;
1136 if (ToCanon != FromCanon)
1137 ICS.Standard.Second = ICK_Derived_To_Base;
1138 }
1139 }
Richard Smith48372b62015-01-27 03:30:40 +00001140 break;
1141
1142 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001143 ICS.setAmbiguous();
1144 ICS.Ambiguous.setFromType(From->getType());
1145 ICS.Ambiguous.setToType(ToType);
1146 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1147 Cand != Conversions.end(); ++Cand)
1148 if (Cand->Viable)
1149 ICS.Ambiguous.addConversion(Cand->Function);
1150 break;
Richard Smith48372b62015-01-27 03:30:40 +00001151
1152 // Fall through.
1153 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001154 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001155 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001156 }
1157
1158 return ICS;
1159}
1160
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001161/// TryImplicitConversion - Attempt to perform an implicit conversion
1162/// from the given expression (Expr) to the given type (ToType). This
1163/// function returns an implicit conversion sequence that can be used
1164/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001165///
1166/// void f(float f);
1167/// void g(int i) { f(i); }
1168///
1169/// this routine would produce an implicit conversion sequence to
1170/// describe the initialization of f from i, which will be a standard
1171/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1172/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1173//
1174/// Note that this routine only determines how the conversion can be
1175/// performed; it does not actually perform the conversion. As such,
1176/// it will not produce any diagnostics if no conversion is available,
1177/// but will instead return an implicit conversion sequence of kind
1178/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001179///
1180/// If @p SuppressUserConversions, then user-defined conversions are
1181/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001182/// If @p AllowExplicit, then explicit user-defined conversions are
1183/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001184///
1185/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1186/// writeback conversion, which allows __autoreleasing id* parameters to
1187/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001188static ImplicitConversionSequence
1189TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1190 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001191 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001192 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001193 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001194 bool AllowObjCWritebackConversion,
1195 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001196 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001197 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001198 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001199 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001200 return ICS;
1201 }
1202
David Blaikiebbafb8a2012-03-11 07:00:24 +00001203 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001204 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001205 return ICS;
1206 }
1207
Douglas Gregor836a7e82010-08-11 02:15:33 +00001208 // C++ [over.ics.user]p4:
1209 // A conversion of an expression of class type to the same class
1210 // type is given Exact Match rank, and a conversion of an
1211 // expression of class type to a base class of that type is
1212 // given Conversion rank, in spite of the fact that a copy/move
1213 // constructor (i.e., a user-defined conversion function) is
1214 // called for those cases.
1215 QualType FromType = From->getType();
1216 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001217 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1218 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001219 ICS.setStandard();
1220 ICS.Standard.setAsIdentityConversion();
1221 ICS.Standard.setFromType(FromType);
1222 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001223
Douglas Gregor5ab11652010-04-17 22:01:05 +00001224 // We don't actually check at this point whether there is a valid
1225 // copy/move constructor, since overloading just assumes that it
1226 // exists. When we actually perform initialization, we'll find the
1227 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001228 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001229
Douglas Gregor5ab11652010-04-17 22:01:05 +00001230 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001231 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001232 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001233
Douglas Gregor836a7e82010-08-11 02:15:33 +00001234 return ICS;
1235 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001237 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1238 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001239 AllowObjCWritebackConversion,
1240 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001241}
1242
John McCall31168b02011-06-15 23:02:42 +00001243ImplicitConversionSequence
1244Sema::TryImplicitConversion(Expr *From, QualType ToType,
1245 bool SuppressUserConversions,
1246 bool AllowExplicit,
1247 bool InOverloadResolution,
1248 bool CStyle,
1249 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001250 return ::TryImplicitConversion(*this, From, ToType,
1251 SuppressUserConversions, AllowExplicit,
1252 InOverloadResolution, CStyle,
1253 AllowObjCWritebackConversion,
1254 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001255}
1256
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001257/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001258/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001259/// converted expression. Flavor is the kind of conversion we're
1260/// performing, used in the error message. If @p AllowExplicit,
1261/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001262ExprResult
1263Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001264 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001265 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001266 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001267}
1268
John Wiegley01296292011-04-08 18:41:53 +00001269ExprResult
1270Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001271 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001272 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001273 if (checkPlaceholderForOverload(*this, From))
1274 return ExprError();
1275
John McCall31168b02011-06-15 23:02:42 +00001276 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1277 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001278 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001279 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001280 if (getLangOpts().ObjC1)
1281 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1282 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001283 ICS = ::TryImplicitConversion(*this, From, ToType,
1284 /*SuppressUserConversions=*/false,
1285 AllowExplicit,
1286 /*InOverloadResolution=*/false,
1287 /*CStyle=*/false,
1288 AllowObjCWritebackConversion,
1289 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001290 return PerformImplicitConversion(From, ToType, ICS, Action);
1291}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001292
1293/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001294/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001295bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1296 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001297 if (Context.hasSameUnqualifiedType(FromType, ToType))
1298 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001299
John McCall991eb4b2010-12-21 00:44:39 +00001300 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1301 // where F adds one of the following at most once:
1302 // - a pointer
1303 // - a member pointer
1304 // - a block pointer
1305 CanQualType CanTo = Context.getCanonicalType(ToType);
1306 CanQualType CanFrom = Context.getCanonicalType(FromType);
1307 Type::TypeClass TyClass = CanTo->getTypeClass();
1308 if (TyClass != CanFrom->getTypeClass()) return false;
1309 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1310 if (TyClass == Type::Pointer) {
1311 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1312 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1313 } else if (TyClass == Type::BlockPointer) {
1314 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1315 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1316 } else if (TyClass == Type::MemberPointer) {
1317 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1318 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1319 } else {
1320 return false;
1321 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001322
John McCall991eb4b2010-12-21 00:44:39 +00001323 TyClass = CanTo->getTypeClass();
1324 if (TyClass != CanFrom->getTypeClass()) return false;
1325 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1326 return false;
1327 }
1328
1329 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1330 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1331 if (!EInfo.getNoReturn()) return false;
1332
1333 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1334 assert(QualType(FromFn, 0).isCanonical());
1335 if (QualType(FromFn, 0) != CanTo) return false;
1336
1337 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001338 return true;
1339}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001340
Douglas Gregor46188682010-05-18 22:42:18 +00001341/// \brief Determine whether the conversion from FromType to ToType is a valid
1342/// vector conversion.
1343///
1344/// \param ICK Will be set to the vector conversion kind, if this is a vector
1345/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001346static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001347 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001348 // We need at least one of these types to be a vector type to have a vector
1349 // conversion.
1350 if (!ToType->isVectorType() && !FromType->isVectorType())
1351 return false;
1352
1353 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001354 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001355 return false;
1356
1357 // There are no conversions between extended vector types, only identity.
1358 if (ToType->isExtVectorType()) {
1359 // There are no conversions between extended vector types other than the
1360 // identity conversion.
1361 if (FromType->isExtVectorType())
1362 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363
Douglas Gregor46188682010-05-18 22:42:18 +00001364 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001365 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001366 ICK = ICK_Vector_Splat;
1367 return true;
1368 }
1369 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001370
1371 // We can perform the conversion between vector types in the following cases:
1372 // 1)vector types are equivalent AltiVec and GCC vector types
1373 // 2)lax vector conversions are permitted and the vector types are of the
1374 // same size
1375 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001376 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1377 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001378 ICK = ICK_Vector_Conversion;
1379 return true;
1380 }
Douglas Gregor46188682010-05-18 22:42:18 +00001381 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001382
Douglas Gregor46188682010-05-18 22:42:18 +00001383 return false;
1384}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001385
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001386static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1387 bool InOverloadResolution,
1388 StandardConversionSequence &SCS,
1389 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001390
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001391/// IsStandardConversion - Determines whether there is a standard
1392/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1393/// expression From to the type ToType. Standard conversion sequences
1394/// only consider non-class types; for conversions that involve class
1395/// types, use TryImplicitConversion. If a conversion exists, SCS will
1396/// contain the standard conversion sequence required to perform this
1397/// conversion and this routine will return true. Otherwise, this
1398/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001399static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1400 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001401 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001402 bool CStyle,
1403 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001404 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001405
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001406 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001407 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001408 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001409 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001410 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001411
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001412 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001413 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001414 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001415 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001416 return false;
1417
Mike Stump11289f42009-09-09 15:08:12 +00001418 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001419 }
1420
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001421 // The first conversion can be an lvalue-to-rvalue conversion,
1422 // array-to-pointer conversion, or function-to-pointer conversion
1423 // (C++ 4p1).
1424
John McCall5c32be02010-08-24 20:38:10 +00001425 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001426 DeclAccessPair AccessPair;
1427 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001428 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001429 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001430 // We were able to resolve the address of the overloaded function,
1431 // so we can convert to the type of that function.
1432 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001433 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001434
1435 // we can sometimes resolve &foo<int> regardless of ToType, so check
1436 // if the type matches (identity) or we are converting to bool
1437 if (!S.Context.hasSameUnqualifiedType(
1438 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1439 QualType resultTy;
1440 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001441 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001442 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1443 // otherwise, only a boolean conversion is standard
1444 if (!ToType->isBooleanType())
1445 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001447
Chandler Carruthffce2452011-03-29 08:08:18 +00001448 // Check if the "from" expression is taking the address of an overloaded
1449 // function and recompute the FromType accordingly. Take advantage of the
1450 // fact that non-static member functions *must* have such an address-of
1451 // expression.
1452 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1453 if (Method && !Method->isStatic()) {
1454 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1455 "Non-unary operator on non-static member address");
1456 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1457 == UO_AddrOf &&
1458 "Non-address-of operator on non-static member address");
1459 const Type *ClassType
1460 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1461 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001462 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1463 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1464 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001465 "Non-address-of operator for overloaded function expression");
1466 FromType = S.Context.getPointerType(FromType);
1467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468
Douglas Gregor980fb162010-04-29 18:24:40 +00001469 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001470 assert(S.Context.hasSameType(
1471 FromType,
1472 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001473 } else {
1474 return false;
1475 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001476 }
John McCall154a2fd2011-08-30 00:57:29 +00001477 // Lvalue-to-rvalue conversion (C++11 4.1):
1478 // A glvalue (3.10) of a non-function, non-array type T can
1479 // be converted to a prvalue.
1480 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001481 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001482 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001483 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001484 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001485
Douglas Gregorc79862f2012-04-12 17:51:55 +00001486 // C11 6.3.2.1p2:
1487 // ... if the lvalue has atomic type, the value has the non-atomic version
1488 // of the type of the lvalue ...
1489 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1490 FromType = Atomic->getValueType();
1491
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001492 // If T is a non-class type, the type of the rvalue is the
1493 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001494 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1495 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001496 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001497 } else if (FromType->isArrayType()) {
1498 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001499 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001500
1501 // An lvalue or rvalue of type "array of N T" or "array of unknown
1502 // bound of T" can be converted to an rvalue of type "pointer to
1503 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001504 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001505
John McCall5c32be02010-08-24 20:38:10 +00001506 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001507 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001508 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001509
1510 // For the purpose of ranking in overload resolution
1511 // (13.3.3.1.1), this conversion is considered an
1512 // array-to-pointer conversion followed by a qualification
1513 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001514 SCS.Second = ICK_Identity;
1515 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001516 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001517 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001518 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001519 }
John McCall086a4642010-11-24 05:12:34 +00001520 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001521 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001522 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001523
1524 // An lvalue of function type T can be converted to an rvalue of
1525 // type "pointer to T." The result is a pointer to the
1526 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001527 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001528 } else {
1529 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001530 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001532 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001533
1534 // The second conversion can be an integral promotion, floating
1535 // point promotion, integral conversion, floating point conversion,
1536 // floating-integral conversion, pointer conversion,
1537 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001538 // For overloading in C, this can also be a "compatible-type"
1539 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001540 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001541 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001542 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001543 // The unqualified versions of the types are the same: there's no
1544 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001545 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001546 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001547 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001548 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001549 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001550 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001551 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001552 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001553 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001554 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001555 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001556 SCS.Second = ICK_Complex_Promotion;
1557 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001558 } else if (ToType->isBooleanType() &&
1559 (FromType->isArithmeticType() ||
1560 FromType->isAnyPointerType() ||
1561 FromType->isBlockPointerType() ||
1562 FromType->isMemberPointerType() ||
1563 FromType->isNullPtrType())) {
1564 // Boolean conversions (C++ 4.12).
1565 SCS.Second = ICK_Boolean_Conversion;
1566 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001567 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001568 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001569 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001570 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001571 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001572 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001573 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001574 SCS.Second = ICK_Complex_Conversion;
1575 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001576 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1577 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001578 // Complex-real conversions (C99 6.3.1.7)
1579 SCS.Second = ICK_Complex_Real;
1580 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001581 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001582 // Floating point conversions (C++ 4.8).
1583 SCS.Second = ICK_Floating_Conversion;
1584 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001585 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001586 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001587 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001588 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001589 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001590 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001591 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001592 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001593 SCS.Second = ICK_Block_Pointer_Conversion;
1594 } else if (AllowObjCWritebackConversion &&
1595 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1596 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001597 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1598 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001599 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001600 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001601 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001602 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001603 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001604 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001605 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001606 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001607 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001608 SCS.Second = SecondICK;
1609 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001610 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001611 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001612 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001613 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001614 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001615 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001616 // Treat a conversion that strips "noreturn" as an identity conversion.
1617 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001618 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1619 InOverloadResolution,
1620 SCS, CStyle)) {
1621 SCS.Second = ICK_TransparentUnionConversion;
1622 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001623 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1624 CStyle)) {
1625 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001626 // appropriately.
1627 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001628 } else if (ToType->isEventT() &&
1629 From->isIntegerConstantExpr(S.getASTContext()) &&
1630 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1631 SCS.Second = ICK_Zero_Event_Conversion;
1632 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001633 } else {
1634 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001635 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001636 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001637 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001639 QualType CanonFrom;
1640 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001641 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001642 bool ObjCLifetimeConversion;
1643 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1644 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001645 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001646 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001647 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001648 CanonFrom = S.Context.getCanonicalType(FromType);
1649 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001650 } else {
1651 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001652 SCS.Third = ICK_Identity;
1653
Mike Stump11289f42009-09-09 15:08:12 +00001654 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001655 // [...] Any difference in top-level cv-qualification is
1656 // subsumed by the initialization itself and does not constitute
1657 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001658 CanonFrom = S.Context.getCanonicalType(FromType);
1659 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001660 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001661 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001662 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001663 FromType = ToType;
1664 CanonFrom = CanonTo;
1665 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001666 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001667 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001668
1669 // If we have not converted the argument type to the parameter type,
1670 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001671 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001672 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001673
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001674 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001676
1677static bool
1678IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1679 QualType &ToType,
1680 bool InOverloadResolution,
1681 StandardConversionSequence &SCS,
1682 bool CStyle) {
1683
1684 const RecordType *UT = ToType->getAsUnionType();
1685 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1686 return false;
1687 // The field to initialize within the transparent union.
1688 RecordDecl *UD = UT->getDecl();
1689 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001690 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001691 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1692 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001693 ToType = it->getType();
1694 return true;
1695 }
1696 }
1697 return false;
1698}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001699
1700/// IsIntegralPromotion - Determines whether the conversion from the
1701/// expression From (whose potentially-adjusted type is FromType) to
1702/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1703/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001704bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001705 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001706 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001707 if (!To) {
1708 return false;
1709 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001710
1711 // An rvalue of type char, signed char, unsigned char, short int, or
1712 // unsigned short int can be converted to an rvalue of type int if
1713 // int can represent all the values of the source type; otherwise,
1714 // the source rvalue can be converted to an rvalue of type unsigned
1715 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001716 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1717 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718 if (// We can promote any signed, promotable integer type to an int
1719 (FromType->isSignedIntegerType() ||
1720 // We can promote any unsigned integer type whose size is
1721 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001722 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001723 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001724 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001725 }
1726
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001727 return To->getKind() == BuiltinType::UInt;
1728 }
1729
Richard Smithb9c5a602012-09-13 21:18:54 +00001730 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001731 // A prvalue of an unscoped enumeration type whose underlying type is not
1732 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1733 // following types that can represent all the values of the enumeration
1734 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1735 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001736 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001737 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001738 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001739 // with lowest integer conversion rank (4.13) greater than the rank of long
1740 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001741 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001742 // C++11 [conv.prom]p4:
1743 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1744 // can be converted to a prvalue of its underlying type. Moreover, if
1745 // integral promotion can be applied to its underlying type, a prvalue of an
1746 // unscoped enumeration type whose underlying type is fixed can also be
1747 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001748 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1749 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1750 // provided for a scoped enumeration.
1751 if (FromEnumType->getDecl()->isScoped())
1752 return false;
1753
Richard Smithb9c5a602012-09-13 21:18:54 +00001754 // We can perform an integral promotion to the underlying type of the enum,
1755 // even if that's not the promoted type.
1756 if (FromEnumType->getDecl()->isFixed()) {
1757 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1758 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1759 IsIntegralPromotion(From, Underlying, ToType);
1760 }
1761
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001762 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001763 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001764 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001765 return Context.hasSameUnqualifiedType(ToType,
1766 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001767 }
John McCall56774992009-12-09 09:09:27 +00001768
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001769 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001770 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1771 // to an rvalue a prvalue of the first of the following types that can
1772 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001773 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001775 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001776 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001777 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001778 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001779 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001780 // Determine whether the type we're converting from is signed or
1781 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001782 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001783 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001784
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001785 // The types we'll try to promote to, in the appropriate
1786 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001787 QualType PromoteTypes[6] = {
1788 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001789 Context.LongTy, Context.UnsignedLongTy ,
1790 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001791 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001792 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001793 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1794 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001795 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001796 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1797 // We found the type that we can promote to. If this is the
1798 // type we wanted, we have a promotion. Otherwise, no
1799 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001800 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001801 }
1802 }
1803 }
1804
1805 // An rvalue for an integral bit-field (9.6) can be converted to an
1806 // rvalue of type int if int can represent all the values of the
1807 // bit-field; otherwise, it can be converted to unsigned int if
1808 // unsigned int can represent all the values of the bit-field. If
1809 // the bit-field is larger yet, no integral promotion applies to
1810 // it. If the bit-field has an enumerated type, it is treated as any
1811 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001812 // FIXME: We should delay checking of bit-fields until we actually perform the
1813 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001814 using llvm::APSInt;
1815 if (From)
John McCalld25db7e2013-05-06 21:39:12 +00001816 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001817 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001818 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001819 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1820 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1821 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001822
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001823 // Are we promoting to an int from a bitfield that fits in an int?
1824 if (BitWidth < ToSize ||
1825 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1826 return To->getKind() == BuiltinType::Int;
1827 }
Mike Stump11289f42009-09-09 15:08:12 +00001828
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001829 // Are we promoting to an unsigned int from an unsigned bitfield
1830 // that fits into an unsigned int?
1831 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1832 return To->getKind() == BuiltinType::UInt;
1833 }
Mike Stump11289f42009-09-09 15:08:12 +00001834
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001835 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001836 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001837 }
Mike Stump11289f42009-09-09 15:08:12 +00001838
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001839 // An rvalue of type bool can be converted to an rvalue of type int,
1840 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001841 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001842 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001843 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001844
1845 return false;
1846}
1847
1848/// IsFloatingPointPromotion - Determines whether the conversion from
1849/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1850/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001851bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001852 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1853 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001854 /// An rvalue of type float can be converted to an rvalue of type
1855 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001856 if (FromBuiltin->getKind() == BuiltinType::Float &&
1857 ToBuiltin->getKind() == BuiltinType::Double)
1858 return true;
1859
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001860 // C99 6.3.1.5p1:
1861 // When a float is promoted to double or long double, or a
1862 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001863 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001864 (FromBuiltin->getKind() == BuiltinType::Float ||
1865 FromBuiltin->getKind() == BuiltinType::Double) &&
1866 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1867 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001868
1869 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001870 if (!getLangOpts().NativeHalfType &&
1871 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001872 ToBuiltin->getKind() == BuiltinType::Float)
1873 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001874 }
1875
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001876 return false;
1877}
1878
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001879/// \brief Determine if a conversion is a complex promotion.
1880///
1881/// A complex promotion is defined as a complex -> complex conversion
1882/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001883/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001884bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001885 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001886 if (!FromComplex)
1887 return false;
1888
John McCall9dd450b2009-09-21 23:43:11 +00001889 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001890 if (!ToComplex)
1891 return false;
1892
1893 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001894 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001895 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001896 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001897}
1898
Douglas Gregor237f96c2008-11-26 23:31:11 +00001899/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1900/// the pointer type FromPtr to a pointer to type ToPointee, with the
1901/// same type qualifiers as FromPtr has on its pointee type. ToType,
1902/// if non-empty, will be a pointer to ToType that may or may not have
1903/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001904///
Mike Stump11289f42009-09-09 15:08:12 +00001905static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001906BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001907 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001908 ASTContext &Context,
1909 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001910 assert((FromPtr->getTypeClass() == Type::Pointer ||
1911 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1912 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001913
John McCall31168b02011-06-15 23:02:42 +00001914 /// Conversions to 'id' subsume cv-qualifier conversions.
1915 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001916 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001917
1918 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001919 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001920 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001921 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001922
John McCall31168b02011-06-15 23:02:42 +00001923 if (StripObjCLifetime)
1924 Quals.removeObjCLifetime();
1925
Mike Stump11289f42009-09-09 15:08:12 +00001926 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001927 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001928 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001929 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001930 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001931
1932 // Build a pointer to ToPointee. It has the right qualifiers
1933 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001934 if (isa<ObjCObjectPointerType>(ToType))
1935 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001936 return Context.getPointerType(ToPointee);
1937 }
1938
1939 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001940 QualType QualifiedCanonToPointee
1941 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001942
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001943 if (isa<ObjCObjectPointerType>(ToType))
1944 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1945 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001946}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001947
Mike Stump11289f42009-09-09 15:08:12 +00001948static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001949 bool InOverloadResolution,
1950 ASTContext &Context) {
1951 // Handle value-dependent integral null pointer constants correctly.
1952 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1953 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001954 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001955 return !InOverloadResolution;
1956
Douglas Gregor56751b52009-09-25 04:25:58 +00001957 return Expr->isNullPointerConstant(Context,
1958 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1959 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001960}
Mike Stump11289f42009-09-09 15:08:12 +00001961
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001962/// IsPointerConversion - Determines whether the conversion of the
1963/// expression From, which has the (possibly adjusted) type FromType,
1964/// can be converted to the type ToType via a pointer conversion (C++
1965/// 4.10). If so, returns true and places the converted type (that
1966/// might differ from ToType in its cv-qualifiers at some level) into
1967/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001968///
Douglas Gregora29dc052008-11-27 01:19:21 +00001969/// This routine also supports conversions to and from block pointers
1970/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1971/// pointers to interfaces. FIXME: Once we've determined the
1972/// appropriate overloading rules for Objective-C, we may want to
1973/// split the Objective-C checks into a different routine; however,
1974/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001975/// conversions, so for now they live here. IncompatibleObjC will be
1976/// set if the conversion is an allowed Objective-C conversion that
1977/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001978bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001979 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001980 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001981 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001982 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001983 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1984 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001985 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001986
Mike Stump11289f42009-09-09 15:08:12 +00001987 // Conversion from a null pointer constant to any Objective-C pointer type.
1988 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001989 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001990 ConvertedType = ToType;
1991 return true;
1992 }
1993
Douglas Gregor231d1c62008-11-27 00:15:41 +00001994 // Blocks: Block pointers can be converted to void*.
1995 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001996 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001997 ConvertedType = ToType;
1998 return true;
1999 }
2000 // Blocks: A null pointer constant can be converted to a block
2001 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002002 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002003 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002004 ConvertedType = ToType;
2005 return true;
2006 }
2007
Sebastian Redl576fd422009-05-10 18:38:11 +00002008 // If the left-hand-side is nullptr_t, the right side can be a null
2009 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002010 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002011 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002012 ConvertedType = ToType;
2013 return true;
2014 }
2015
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002016 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002017 if (!ToTypePtr)
2018 return false;
2019
2020 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002021 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002022 ConvertedType = ToType;
2023 return true;
2024 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002025
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002026 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002027 // , including objective-c pointers.
2028 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002029 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002030 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002031 ConvertedType = BuildSimilarlyQualifiedPointerType(
2032 FromType->getAs<ObjCObjectPointerType>(),
2033 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002034 ToType, Context);
2035 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002036 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002037 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002038 if (!FromTypePtr)
2039 return false;
2040
2041 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002042
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002043 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002044 // pointer conversion, so don't do all of the work below.
2045 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2046 return false;
2047
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002048 // An rvalue of type "pointer to cv T," where T is an object type,
2049 // can be converted to an rvalue of type "pointer to cv void" (C++
2050 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002051 if (FromPointeeType->isIncompleteOrObjectType() &&
2052 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002053 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002054 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002055 ToType, Context,
2056 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002057 return true;
2058 }
2059
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002060 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002061 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002062 ToPointeeType->isVoidType()) {
2063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2064 ToPointeeType,
2065 ToType, Context);
2066 return true;
2067 }
2068
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002069 // When we're overloading in C, we allow a special kind of pointer
2070 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002071 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002072 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002073 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002074 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002075 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002076 return true;
2077 }
2078
Douglas Gregor5c407d92008-10-23 00:40:37 +00002079 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002080 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002081 // An rvalue of type "pointer to cv D," where D is a class type,
2082 // can be converted to an rvalue of type "pointer to cv B," where
2083 // B is a base class (clause 10) of D. If B is an inaccessible
2084 // (clause 11) or ambiguous (10.2) base class of D, a program that
2085 // necessitates this conversion is ill-formed. The result of the
2086 // conversion is a pointer to the base class sub-object of the
2087 // derived class object. The null pointer value is converted to
2088 // the null pointer value of the destination type.
2089 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002090 // Note that we do not check for ambiguity or inaccessibility
2091 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002092 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002093 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002094 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002095 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002096 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002097 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002098 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002099 ToType, Context);
2100 return true;
2101 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002102
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002103 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2104 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2105 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2106 ToPointeeType,
2107 ToType, Context);
2108 return true;
2109 }
2110
Douglas Gregora119f102008-12-19 19:13:09 +00002111 return false;
2112}
Douglas Gregoraec25842011-04-26 23:16:46 +00002113
2114/// \brief Adopt the given qualifiers for the given type.
2115static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2116 Qualifiers TQs = T.getQualifiers();
2117
2118 // Check whether qualifiers already match.
2119 if (TQs == Qs)
2120 return T;
2121
2122 if (Qs.compatiblyIncludes(TQs))
2123 return Context.getQualifiedType(T, Qs);
2124
2125 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2126}
Douglas Gregora119f102008-12-19 19:13:09 +00002127
2128/// isObjCPointerConversion - Determines whether this is an
2129/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2130/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002131bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002132 QualType& ConvertedType,
2133 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002134 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002135 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002136
Douglas Gregoraec25842011-04-26 23:16:46 +00002137 // The set of qualifiers on the type we're converting from.
2138 Qualifiers FromQualifiers = FromType.getQualifiers();
2139
Steve Naroff7cae42b2009-07-10 23:34:53 +00002140 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002141 const ObjCObjectPointerType* ToObjCPtr =
2142 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002143 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002144 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002145
Steve Naroff7cae42b2009-07-10 23:34:53 +00002146 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002147 // If the pointee types are the same (ignoring qualifications),
2148 // then this is not a pointer conversion.
2149 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2150 FromObjCPtr->getPointeeType()))
2151 return false;
2152
Douglas Gregoraec25842011-04-26 23:16:46 +00002153 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002154 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002155 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002156 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002157 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002158 return true;
2159 }
2160 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002161 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002162 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002163 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002164 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002165 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002166 return true;
2167 }
2168 // Objective C++: We're able to convert from a pointer to an
2169 // interface to a pointer to a different interface.
2170 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002171 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2172 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002173 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002174 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2175 FromObjCPtr->getPointeeType()))
2176 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002177 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002178 ToObjCPtr->getPointeeType(),
2179 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002180 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002181 return true;
2182 }
2183
2184 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2185 // Okay: this is some kind of implicit downcast of Objective-C
2186 // interfaces, which is permitted. However, we're going to
2187 // complain about it.
2188 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002189 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002190 ToObjCPtr->getPointeeType(),
2191 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002192 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002193 return true;
2194 }
Mike Stump11289f42009-09-09 15:08:12 +00002195 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002196 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002197 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002198 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002199 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002200 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002201 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002202 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002203 // to a block pointer type.
2204 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002205 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002206 return true;
2207 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002208 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002210 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002211 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002212 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002213 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002214 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002215 return true;
2216 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002217 else
Douglas Gregora119f102008-12-19 19:13:09 +00002218 return false;
2219
Douglas Gregor033f56d2008-12-23 00:53:59 +00002220 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002221 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002222 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002223 else if (const BlockPointerType *FromBlockPtr =
2224 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002225 FromPointeeType = FromBlockPtr->getPointeeType();
2226 else
Douglas Gregora119f102008-12-19 19:13:09 +00002227 return false;
2228
Douglas Gregora119f102008-12-19 19:13:09 +00002229 // If we have pointers to pointers, recursively check whether this
2230 // is an Objective-C conversion.
2231 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2232 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2233 IncompatibleObjC)) {
2234 // We always complain about this conversion.
2235 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002236 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002237 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002238 return true;
2239 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002240 // Allow conversion of pointee being objective-c pointer to another one;
2241 // as in I* to id.
2242 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2243 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2244 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2245 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002246
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002247 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002248 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002249 return true;
2250 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002251
Douglas Gregor033f56d2008-12-23 00:53:59 +00002252 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002253 // differences in the argument and result types are in Objective-C
2254 // pointer conversions. If so, we permit the conversion (but
2255 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002256 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002257 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002258 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002259 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002260 if (FromFunctionType && ToFunctionType) {
2261 // If the function types are exactly the same, this isn't an
2262 // Objective-C pointer conversion.
2263 if (Context.getCanonicalType(FromPointeeType)
2264 == Context.getCanonicalType(ToPointeeType))
2265 return false;
2266
2267 // Perform the quick checks that will tell us whether these
2268 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002269 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002270 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2271 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2272 return false;
2273
2274 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002275 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2276 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002277 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002278 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2279 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002280 ConvertedType, IncompatibleObjC)) {
2281 // Okay, we have an Objective-C pointer conversion.
2282 HasObjCConversion = true;
2283 } else {
2284 // Function types are too different. Abort.
2285 return false;
2286 }
Mike Stump11289f42009-09-09 15:08:12 +00002287
Douglas Gregora119f102008-12-19 19:13:09 +00002288 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002289 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002290 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002291 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2292 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002293 if (Context.getCanonicalType(FromArgType)
2294 == Context.getCanonicalType(ToArgType)) {
2295 // Okay, the types match exactly. Nothing to do.
2296 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2297 ConvertedType, IncompatibleObjC)) {
2298 // Okay, we have an Objective-C pointer conversion.
2299 HasObjCConversion = true;
2300 } else {
2301 // Argument types are too different. Abort.
2302 return false;
2303 }
2304 }
2305
2306 if (HasObjCConversion) {
2307 // We had an Objective-C conversion. Allow this pointer
2308 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002309 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002310 IncompatibleObjC = true;
2311 return true;
2312 }
2313 }
2314
Sebastian Redl72b597d2009-01-25 19:43:20 +00002315 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002316}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002317
John McCall31168b02011-06-15 23:02:42 +00002318/// \brief Determine whether this is an Objective-C writeback conversion,
2319/// used for parameter passing when performing automatic reference counting.
2320///
2321/// \param FromType The type we're converting form.
2322///
2323/// \param ToType The type we're converting to.
2324///
2325/// \param ConvertedType The type that will be produced after applying
2326/// this conversion.
2327bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2328 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002329 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002330 Context.hasSameUnqualifiedType(FromType, ToType))
2331 return false;
2332
2333 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2334 QualType ToPointee;
2335 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2336 ToPointee = ToPointer->getPointeeType();
2337 else
2338 return false;
2339
2340 Qualifiers ToQuals = ToPointee.getQualifiers();
2341 if (!ToPointee->isObjCLifetimeType() ||
2342 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002343 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002344 return false;
2345
2346 // Argument must be a pointer to __strong to __weak.
2347 QualType FromPointee;
2348 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2349 FromPointee = FromPointer->getPointeeType();
2350 else
2351 return false;
2352
2353 Qualifiers FromQuals = FromPointee.getQualifiers();
2354 if (!FromPointee->isObjCLifetimeType() ||
2355 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2356 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2357 return false;
2358
2359 // Make sure that we have compatible qualifiers.
2360 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2361 if (!ToQuals.compatiblyIncludes(FromQuals))
2362 return false;
2363
2364 // Remove qualifiers from the pointee type we're converting from; they
2365 // aren't used in the compatibility check belong, and we'll be adding back
2366 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2367 FromPointee = FromPointee.getUnqualifiedType();
2368
2369 // The unqualified form of the pointee types must be compatible.
2370 ToPointee = ToPointee.getUnqualifiedType();
2371 bool IncompatibleObjC;
2372 if (Context.typesAreCompatible(FromPointee, ToPointee))
2373 FromPointee = ToPointee;
2374 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2375 IncompatibleObjC))
2376 return false;
2377
2378 /// \brief Construct the type we're converting to, which is a pointer to
2379 /// __autoreleasing pointee.
2380 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2381 ConvertedType = Context.getPointerType(FromPointee);
2382 return true;
2383}
2384
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002385bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2386 QualType& ConvertedType) {
2387 QualType ToPointeeType;
2388 if (const BlockPointerType *ToBlockPtr =
2389 ToType->getAs<BlockPointerType>())
2390 ToPointeeType = ToBlockPtr->getPointeeType();
2391 else
2392 return false;
2393
2394 QualType FromPointeeType;
2395 if (const BlockPointerType *FromBlockPtr =
2396 FromType->getAs<BlockPointerType>())
2397 FromPointeeType = FromBlockPtr->getPointeeType();
2398 else
2399 return false;
2400 // We have pointer to blocks, check whether the only
2401 // differences in the argument and result types are in Objective-C
2402 // pointer conversions. If so, we permit the conversion.
2403
2404 const FunctionProtoType *FromFunctionType
2405 = FromPointeeType->getAs<FunctionProtoType>();
2406 const FunctionProtoType *ToFunctionType
2407 = ToPointeeType->getAs<FunctionProtoType>();
2408
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002409 if (!FromFunctionType || !ToFunctionType)
2410 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002411
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002412 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002413 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002414
2415 // Perform the quick checks that will tell us whether these
2416 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002417 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002418 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2419 return false;
2420
2421 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2422 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2423 if (FromEInfo != ToEInfo)
2424 return false;
2425
2426 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002427 if (Context.hasSameType(FromFunctionType->getReturnType(),
2428 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002429 // Okay, the types match exactly. Nothing to do.
2430 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002431 QualType RHS = FromFunctionType->getReturnType();
2432 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002433 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002434 !RHS.hasQualifiers() && LHS.hasQualifiers())
2435 LHS = LHS.getUnqualifiedType();
2436
2437 if (Context.hasSameType(RHS,LHS)) {
2438 // OK exact match.
2439 } else if (isObjCPointerConversion(RHS, LHS,
2440 ConvertedType, IncompatibleObjC)) {
2441 if (IncompatibleObjC)
2442 return false;
2443 // Okay, we have an Objective-C pointer conversion.
2444 }
2445 else
2446 return false;
2447 }
2448
2449 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002450 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002451 ArgIdx != NumArgs; ++ArgIdx) {
2452 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002453 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2454 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002455 if (Context.hasSameType(FromArgType, ToArgType)) {
2456 // Okay, the types match exactly. Nothing to do.
2457 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2458 ConvertedType, IncompatibleObjC)) {
2459 if (IncompatibleObjC)
2460 return false;
2461 // Okay, we have an Objective-C pointer conversion.
2462 } else
2463 // Argument types are too different. Abort.
2464 return false;
2465 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002466 if (LangOpts.ObjCAutoRefCount &&
2467 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2468 ToFunctionType))
2469 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002470
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002471 ConvertedType = ToType;
2472 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002473}
2474
Richard Trieucaff2472011-11-23 22:32:32 +00002475enum {
2476 ft_default,
2477 ft_different_class,
2478 ft_parameter_arity,
2479 ft_parameter_mismatch,
2480 ft_return_type,
2481 ft_qualifer_mismatch
2482};
2483
2484/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2485/// function types. Catches different number of parameter, mismatch in
2486/// parameter types, and different return types.
2487void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2488 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002489 // If either type is not valid, include no extra info.
2490 if (FromType.isNull() || ToType.isNull()) {
2491 PDiag << ft_default;
2492 return;
2493 }
2494
Richard Trieucaff2472011-11-23 22:32:32 +00002495 // Get the function type from the pointers.
2496 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2497 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2498 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002499 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002500 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2501 << QualType(FromMember->getClass(), 0);
2502 return;
2503 }
2504 FromType = FromMember->getPointeeType();
2505 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002506 }
2507
Richard Trieu96ed5b62011-12-13 23:19:45 +00002508 if (FromType->isPointerType())
2509 FromType = FromType->getPointeeType();
2510 if (ToType->isPointerType())
2511 ToType = ToType->getPointeeType();
2512
2513 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002514 FromType = FromType.getNonReferenceType();
2515 ToType = ToType.getNonReferenceType();
2516
Richard Trieucaff2472011-11-23 22:32:32 +00002517 // Don't print extra info for non-specialized template functions.
2518 if (FromType->isInstantiationDependentType() &&
2519 !FromType->getAs<TemplateSpecializationType>()) {
2520 PDiag << ft_default;
2521 return;
2522 }
2523
Richard Trieu96ed5b62011-12-13 23:19:45 +00002524 // No extra info for same types.
2525 if (Context.hasSameType(FromType, ToType)) {
2526 PDiag << ft_default;
2527 return;
2528 }
2529
Richard Trieucaff2472011-11-23 22:32:32 +00002530 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2531 *ToFunction = ToType->getAs<FunctionProtoType>();
2532
2533 // Both types need to be function types.
2534 if (!FromFunction || !ToFunction) {
2535 PDiag << ft_default;
2536 return;
2537 }
2538
Alp Toker9cacbab2014-01-20 20:26:09 +00002539 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2540 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2541 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002542 return;
2543 }
2544
2545 // Handle different parameter types.
2546 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002547 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002548 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002549 << ToFunction->getParamType(ArgPos)
2550 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002551 return;
2552 }
2553
2554 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002555 if (!Context.hasSameType(FromFunction->getReturnType(),
2556 ToFunction->getReturnType())) {
2557 PDiag << ft_return_type << ToFunction->getReturnType()
2558 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002559 return;
2560 }
2561
2562 unsigned FromQuals = FromFunction->getTypeQuals(),
2563 ToQuals = ToFunction->getTypeQuals();
2564 if (FromQuals != ToQuals) {
2565 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2566 return;
2567 }
2568
2569 // Unable to find a difference, so add no extra info.
2570 PDiag << ft_default;
2571}
2572
Alp Toker9cacbab2014-01-20 20:26:09 +00002573/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002574/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002575/// they have same number of arguments. If the parameters are different,
2576/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002577bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2578 const FunctionProtoType *NewType,
2579 unsigned *ArgPos) {
2580 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2581 N = NewType->param_type_begin(),
2582 E = OldType->param_type_end();
2583 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002584 if (!Context.hasSameType(O->getUnqualifiedType(),
2585 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002586 if (ArgPos)
2587 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002588 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002589 }
2590 }
2591 return true;
2592}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002593
Douglas Gregor39c16d42008-10-24 04:54:22 +00002594/// CheckPointerConversion - Check the pointer conversion from the
2595/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002596/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002597/// conversions for which IsPointerConversion has already returned
2598/// true. It returns true and produces a diagnostic if there was an
2599/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002600bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002601 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002602 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002603 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002604 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002605 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002606
John McCall8cb679e2010-11-15 09:13:47 +00002607 Kind = CK_BitCast;
2608
David Blaikie1c7c8f72012-08-08 17:33:31 +00002609 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002610 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002611 Expr::NPCK_ZeroExpression) {
2612 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2613 DiagRuntimeBehavior(From->getExprLoc(), From,
2614 PDiag(diag::warn_impcast_bool_to_null_pointer)
2615 << ToType << From->getSourceRange());
2616 else if (!isUnevaluatedContext())
2617 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2618 << ToType << From->getSourceRange();
2619 }
John McCall9320b872011-09-09 05:25:32 +00002620 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2621 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002622 QualType FromPointeeType = FromPtrType->getPointeeType(),
2623 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002624
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002625 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2626 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002627 // We must have a derived-to-base conversion. Check an
2628 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002629 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2630 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002631 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002632 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002633 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002634
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002635 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002636 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002637 }
2638 }
John McCall9320b872011-09-09 05:25:32 +00002639 } else if (const ObjCObjectPointerType *ToPtrType =
2640 ToType->getAs<ObjCObjectPointerType>()) {
2641 if (const ObjCObjectPointerType *FromPtrType =
2642 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002643 // Objective-C++ conversions are always okay.
2644 // FIXME: We should have a different class of conversions for the
2645 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002646 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002647 return false;
John McCall9320b872011-09-09 05:25:32 +00002648 } else if (FromType->isBlockPointerType()) {
2649 Kind = CK_BlockPointerToObjCPointerCast;
2650 } else {
2651 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002652 }
John McCall9320b872011-09-09 05:25:32 +00002653 } else if (ToType->isBlockPointerType()) {
2654 if (!FromType->isBlockPointerType())
2655 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002656 }
John McCall8cb679e2010-11-15 09:13:47 +00002657
2658 // We shouldn't fall into this case unless it's valid for other
2659 // reasons.
2660 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2661 Kind = CK_NullToPointer;
2662
Douglas Gregor39c16d42008-10-24 04:54:22 +00002663 return false;
2664}
2665
Sebastian Redl72b597d2009-01-25 19:43:20 +00002666/// IsMemberPointerConversion - Determines whether the conversion of the
2667/// expression From, which has the (possibly adjusted) type FromType, can be
2668/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2669/// If so, returns true and places the converted type (that might differ from
2670/// ToType in its cv-qualifiers at some level) into ConvertedType.
2671bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002672 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002673 bool InOverloadResolution,
2674 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002675 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002676 if (!ToTypePtr)
2677 return false;
2678
2679 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002680 if (From->isNullPointerConstant(Context,
2681 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2682 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002683 ConvertedType = ToType;
2684 return true;
2685 }
2686
2687 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002688 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002689 if (!FromTypePtr)
2690 return false;
2691
2692 // A pointer to member of B can be converted to a pointer to member of D,
2693 // where D is derived from B (C++ 4.11p2).
2694 QualType FromClass(FromTypePtr->getClass(), 0);
2695 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002696
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002697 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002698 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002699 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002700 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2701 ToClass.getTypePtr());
2702 return true;
2703 }
2704
2705 return false;
2706}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002707
Sebastian Redl72b597d2009-01-25 19:43:20 +00002708/// CheckMemberPointerConversion - Check the member pointer conversion from the
2709/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002710/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002711/// for which IsMemberPointerConversion has already returned true. It returns
2712/// true and produces a diagnostic if there was an error, or returns false
2713/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002714bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002715 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002716 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002717 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002718 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002719 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002720 if (!FromPtrType) {
2721 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002722 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002723 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002724 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002725 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002726 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002727 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002728
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002729 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002730 assert(ToPtrType && "No member pointer cast has a target type "
2731 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002732
Sebastian Redled8f2002009-01-28 18:33:18 +00002733 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2734 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002735
Sebastian Redled8f2002009-01-28 18:33:18 +00002736 // FIXME: What about dependent types?
2737 assert(FromClass->isRecordType() && "Pointer into non-class.");
2738 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002739
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002740 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002741 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002742 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2743 assert(DerivationOkay &&
2744 "Should not have been called if derivation isn't OK.");
2745 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002746
Sebastian Redled8f2002009-01-28 18:33:18 +00002747 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2748 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002749 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2750 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2751 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2752 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002753 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002754
Douglas Gregor89ee6822009-02-28 01:32:25 +00002755 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002756 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2757 << FromClass << ToClass << QualType(VBase, 0)
2758 << From->getSourceRange();
2759 return true;
2760 }
2761
John McCall5b0829a2010-02-10 09:31:12 +00002762 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002763 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2764 Paths.front(),
2765 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002766
Anders Carlssond7923c62009-08-22 23:33:40 +00002767 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002768 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002769 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002770 return false;
2771}
2772
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002773/// Determine whether the lifetime conversion between the two given
2774/// qualifiers sets is nontrivial.
2775static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2776 Qualifiers ToQuals) {
2777 // Converting anything to const __unsafe_unretained is trivial.
2778 if (ToQuals.hasConst() &&
2779 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2780 return false;
2781
2782 return true;
2783}
2784
Douglas Gregor9a657932008-10-21 23:43:52 +00002785/// IsQualificationConversion - Determines whether the conversion from
2786/// an rvalue of type FromType to ToType is a qualification conversion
2787/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002788///
2789/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2790/// when the qualification conversion involves a change in the Objective-C
2791/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002792bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002793Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002794 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002795 FromType = Context.getCanonicalType(FromType);
2796 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002797 ObjCLifetimeConversion = false;
2798
Douglas Gregor9a657932008-10-21 23:43:52 +00002799 // If FromType and ToType are the same type, this is not a
2800 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002801 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002802 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002803
Douglas Gregor9a657932008-10-21 23:43:52 +00002804 // (C++ 4.4p4):
2805 // A conversion can add cv-qualifiers at levels other than the first
2806 // in multi-level pointers, subject to the following rules: [...]
2807 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002808 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002809 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002810 // Within each iteration of the loop, we check the qualifiers to
2811 // determine if this still looks like a qualification
2812 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002813 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002814 // until there are no more pointers or pointers-to-members left to
2815 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002816 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002817
Douglas Gregor90609aa2011-04-25 18:40:17 +00002818 Qualifiers FromQuals = FromType.getQualifiers();
2819 Qualifiers ToQuals = ToType.getQualifiers();
2820
John McCall31168b02011-06-15 23:02:42 +00002821 // Objective-C ARC:
2822 // Check Objective-C lifetime conversions.
2823 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2824 UnwrappedAnyPointer) {
2825 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002826 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2827 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002828 FromQuals.removeObjCLifetime();
2829 ToQuals.removeObjCLifetime();
2830 } else {
2831 // Qualification conversions cannot cast between different
2832 // Objective-C lifetime qualifiers.
2833 return false;
2834 }
2835 }
2836
Douglas Gregorf30053d2011-05-08 06:09:53 +00002837 // Allow addition/removal of GC attributes but not changing GC attributes.
2838 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2839 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2840 FromQuals.removeObjCGCAttr();
2841 ToQuals.removeObjCGCAttr();
2842 }
2843
Douglas Gregor9a657932008-10-21 23:43:52 +00002844 // -- for every j > 0, if const is in cv 1,j then const is in cv
2845 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002846 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
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 // -- if the cv 1,j and cv 2,j are different, then const is in
2850 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002851 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002852 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002853 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002854
Douglas Gregor9a657932008-10-21 23:43:52 +00002855 // Keep track of whether all prior cv-qualifiers in the "to" type
2856 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002857 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002858 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002859 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002860
2861 // We are left with FromType and ToType being the pointee types
2862 // after unwrapping the original FromType and ToType the same number
2863 // of types. If we unwrapped any pointers, and if FromType and
2864 // ToType have the same unqualified type (since we checked
2865 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002866 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002867}
2868
Douglas Gregorc79862f2012-04-12 17:51:55 +00002869/// \brief - Determine whether this is a conversion from a scalar type to an
2870/// atomic type.
2871///
2872/// If successful, updates \c SCS's second and third steps in the conversion
2873/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002874static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2875 bool InOverloadResolution,
2876 StandardConversionSequence &SCS,
2877 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002878 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2879 if (!ToAtomic)
2880 return false;
2881
2882 StandardConversionSequence InnerSCS;
2883 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2884 InOverloadResolution, InnerSCS,
2885 CStyle, /*AllowObjCWritebackConversion=*/false))
2886 return false;
2887
2888 SCS.Second = InnerSCS.Second;
2889 SCS.setToType(1, InnerSCS.getToType(1));
2890 SCS.Third = InnerSCS.Third;
2891 SCS.QualificationIncludesObjCLifetime
2892 = InnerSCS.QualificationIncludesObjCLifetime;
2893 SCS.setToType(2, InnerSCS.getToType(2));
2894 return true;
2895}
2896
Sebastian Redle5417162012-03-27 18:33:03 +00002897static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2898 CXXConstructorDecl *Constructor,
2899 QualType Type) {
2900 const FunctionProtoType *CtorType =
2901 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002902 if (CtorType->getNumParams() > 0) {
2903 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002904 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2905 return true;
2906 }
2907 return false;
2908}
2909
Sebastian Redl82ace982012-02-11 23:51:08 +00002910static OverloadingResult
2911IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2912 CXXRecordDecl *To,
2913 UserDefinedConversionSequence &User,
2914 OverloadCandidateSet &CandidateSet,
2915 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002916 DeclContext::lookup_result R = S.LookupConstructors(To);
2917 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002918 Con != ConEnd; ++Con) {
2919 NamedDecl *D = *Con;
2920 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2921
2922 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00002923 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002924 FunctionTemplateDecl *ConstructorTmpl
2925 = dyn_cast<FunctionTemplateDecl>(D);
2926 if (ConstructorTmpl)
2927 Constructor
2928 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2929 else
2930 Constructor = cast<CXXConstructorDecl>(D);
2931
2932 bool Usable = !Constructor->isInvalidDecl() &&
2933 S.isInitListConstructor(Constructor) &&
2934 (AllowExplicit || !Constructor->isExplicit());
2935 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002936 // If the first argument is (a reference to) the target type,
2937 // suppress conversions.
2938 bool SuppressUserConversions =
2939 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002940 if (ConstructorTmpl)
2941 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00002942 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002943 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002944 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002945 else
2946 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002947 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002948 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002949 }
2950 }
2951
2952 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2953
2954 OverloadCandidateSet::iterator Best;
2955 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2956 case OR_Success: {
2957 // Record the standard conversion we used and the conversion function.
2958 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002959 QualType ThisType = Constructor->getThisType(S.Context);
2960 // Initializer lists don't have conversions as such.
2961 User.Before.setAsIdentityConversion();
2962 User.HadMultipleCandidates = HadMultipleCandidates;
2963 User.ConversionFunction = Constructor;
2964 User.FoundConversionFunction = Best->FoundDecl;
2965 User.After.setAsIdentityConversion();
2966 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2967 User.After.setAllToTypes(ToType);
2968 return OR_Success;
2969 }
2970
2971 case OR_No_Viable_Function:
2972 return OR_No_Viable_Function;
2973 case OR_Deleted:
2974 return OR_Deleted;
2975 case OR_Ambiguous:
2976 return OR_Ambiguous;
2977 }
2978
2979 llvm_unreachable("Invalid OverloadResult!");
2980}
2981
Douglas Gregor576e98c2009-01-30 23:27:23 +00002982/// Determines whether there is a user-defined conversion sequence
2983/// (C++ [over.ics.user]) that converts expression From to the type
2984/// ToType. If such a conversion exists, User will contain the
2985/// user-defined conversion sequence that performs such a conversion
2986/// and this routine will return true. Otherwise, this routine returns
2987/// false and User is unspecified.
2988///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002989/// \param AllowExplicit true if the conversion should consider C++0x
2990/// "explicit" conversion functions as well as non-explicit conversion
2991/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00002992///
2993/// \param AllowObjCConversionOnExplicit true if the conversion should
2994/// allow an extra Objective-C pointer conversion on uses of explicit
2995/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00002996static OverloadingResult
2997IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002998 UserDefinedConversionSequence &User,
2999 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003000 bool AllowExplicit,
3001 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003002 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003003
Douglas Gregor5ab11652010-04-17 22:01:05 +00003004 // Whether we will only visit constructors.
3005 bool ConstructorsOnly = false;
3006
3007 // If the type we are conversion to is a class type, enumerate its
3008 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003009 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003010 // C++ [over.match.ctor]p1:
3011 // When objects of class type are direct-initialized (8.5), or
3012 // copy-initialized from an expression of the same or a
3013 // derived class type (8.5), overload resolution selects the
3014 // constructor. [...] For copy-initialization, the candidate
3015 // functions are all the converting constructors (12.3.1) of
3016 // that class. The argument list is the expression-list within
3017 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003018 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003019 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003020 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003021 ConstructorsOnly = true;
3022
Benjamin Kramer90633e32012-11-23 17:04:52 +00003023 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003024 // RequireCompleteType may have returned true due to some invalid decl
3025 // during template instantiation, but ToType may be complete enough now
3026 // to try to recover.
3027 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003028 // We're not going to find any constructors.
3029 } else if (CXXRecordDecl *ToRecordDecl
3030 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003031
3032 Expr **Args = &From;
3033 unsigned NumArgs = 1;
3034 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003035 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003036 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003037 OverloadingResult Result = IsInitializerListConstructorConversion(
3038 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3039 if (Result != OR_No_Viable_Function)
3040 return Result;
3041 // Never mind.
3042 CandidateSet.clear();
3043
3044 // If we're list-initializing, we pass the individual elements as
3045 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003046 Args = InitList->getInits();
3047 NumArgs = InitList->getNumInits();
3048 ListInitializing = true;
3049 }
3050
David Blaikieff7d47a2012-12-19 00:45:41 +00003051 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3052 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003053 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003054 NamedDecl *D = *Con;
3055 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3056
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003057 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003058 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003059 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003060 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003061 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003062 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003063 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3064 else
John McCalla0296f72010-03-19 07:35:19 +00003065 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003066
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003067 bool Usable = !Constructor->isInvalidDecl();
3068 if (ListInitializing)
3069 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3070 else
3071 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3072 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003073 bool SuppressUserConversions = !ConstructorsOnly;
3074 if (SuppressUserConversions && ListInitializing) {
3075 SuppressUserConversions = false;
3076 if (NumArgs == 1) {
3077 // If the first argument is (a reference to) the target type,
3078 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003079 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3080 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003081 }
3082 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003083 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003084 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003085 /*ExplicitArgs*/ nullptr,
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 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003089 // Allow one user-defined conversion when user specifies a
3090 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003091 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003092 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003093 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003094 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003095 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003096 }
3097 }
3098
Douglas Gregor5ab11652010-04-17 22:01:05 +00003099 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003100 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003101 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003102 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003103 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003104 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003105 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003106 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3107 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003108 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3109 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003110 DeclAccessPair FoundDecl = I.getPair();
3111 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003112 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3113 if (isa<UsingShadowDecl>(D))
3114 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3115
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003116 CXXConversionDecl *Conv;
3117 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003118 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3119 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003120 else
John McCallda4458e2010-03-31 01:36:47 +00003121 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003122
3123 if (AllowExplicit || !Conv->isExplicit()) {
3124 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003125 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3126 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003127 CandidateSet,
3128 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003129 else
John McCall5c32be02010-08-24 20:38:10 +00003130 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003131 From, ToType, CandidateSet,
3132 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003133 }
3134 }
3135 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003136 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003137
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003138 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3139
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003140 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003141 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3142 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003143 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003144 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003145 // Record the standard conversion we used and the conversion function.
3146 if (CXXConstructorDecl *Constructor
3147 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3148 // C++ [over.ics.user]p1:
3149 // If the user-defined conversion is specified by a
3150 // constructor (12.3.1), the initial standard conversion
3151 // sequence converts the source type to the type required by
3152 // the argument of the constructor.
3153 //
3154 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003155 if (isa<InitListExpr>(From)) {
3156 // Initializer lists don't have conversions as such.
3157 User.Before.setAsIdentityConversion();
3158 } else {
3159 if (Best->Conversions[0].isEllipsis())
3160 User.EllipsisConversion = true;
3161 else {
3162 User.Before = Best->Conversions[0].Standard;
3163 User.EllipsisConversion = false;
3164 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003165 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003166 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003167 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003168 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003169 User.After.setAsIdentityConversion();
3170 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3171 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003172 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003173 }
3174 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003175 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3176 // C++ [over.ics.user]p1:
3177 //
3178 // [...] If the user-defined conversion is specified by a
3179 // conversion function (12.3.2), the initial standard
3180 // conversion sequence converts the source type to the
3181 // implicit object parameter of the conversion function.
3182 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003183 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003184 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003185 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003186 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003187
John McCall5c32be02010-08-24 20:38:10 +00003188 // C++ [over.ics.user]p2:
3189 // The second standard conversion sequence converts the
3190 // result of the user-defined conversion to the target type
3191 // for the sequence. Since an implicit conversion sequence
3192 // is an initialization, the special rules for
3193 // initialization by user-defined conversion apply when
3194 // selecting the best user-defined conversion for a
3195 // user-defined conversion sequence (see 13.3.3 and
3196 // 13.3.3.1).
3197 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003198 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003199 }
David Blaikie8a40f702012-01-17 06:56:22 +00003200 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003201
John McCall5c32be02010-08-24 20:38:10 +00003202 case OR_No_Viable_Function:
3203 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003204
John McCall5c32be02010-08-24 20:38:10 +00003205 case OR_Ambiguous:
3206 return OR_Ambiguous;
3207 }
3208
David Blaikie8a40f702012-01-17 06:56:22 +00003209 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003210}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003211
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003212bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003213Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003214 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003215 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3216 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003217 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003218 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003219 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003220 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003221 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3222 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003223 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003224 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003225 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003226 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003227 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3228 << From->getType() << From->getSourceRange() << ToType;
3229 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003230 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003231 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003232 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003233}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003234
Douglas Gregor2837aa22012-02-22 17:32:19 +00003235/// \brief Compare the user-defined conversion functions or constructors
3236/// of two user-defined conversion sequences to determine whether any ordering
3237/// is possible.
3238static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003239compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003240 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003241 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003242 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003243
Douglas Gregor2837aa22012-02-22 17:32:19 +00003244 // Objective-C++:
3245 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003246 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003247 // respectively, always prefer the conversion to a function pointer,
3248 // because the function pointer is more lightweight and is more likely
3249 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003250 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003251 if (!Conv1)
3252 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003253
Douglas Gregor2837aa22012-02-22 17:32:19 +00003254 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3255 if (!Conv2)
3256 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003257
Douglas Gregor2837aa22012-02-22 17:32:19 +00003258 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3259 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3260 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3261 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003262 return Block1 ? ImplicitConversionSequence::Worse
3263 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003264 }
3265
3266 return ImplicitConversionSequence::Indistinguishable;
3267}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003268
3269static bool hasDeprecatedStringLiteralToCharPtrConversion(
3270 const ImplicitConversionSequence &ICS) {
3271 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3272 (ICS.isUserDefined() &&
3273 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3274}
3275
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003276/// CompareImplicitConversionSequences - Compare two implicit
3277/// conversion sequences to determine whether one is better than the
3278/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003279static ImplicitConversionSequence::CompareKind
3280CompareImplicitConversionSequences(Sema &S,
3281 const ImplicitConversionSequence& ICS1,
3282 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003283{
3284 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3285 // conversion sequences (as defined in 13.3.3.1)
3286 // -- a standard conversion sequence (13.3.3.1.1) is a better
3287 // conversion sequence than a user-defined conversion sequence or
3288 // an ellipsis conversion sequence, and
3289 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3290 // conversion sequence than an ellipsis conversion sequence
3291 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003292 //
John McCall0d1da222010-01-12 00:44:57 +00003293 // C++0x [over.best.ics]p10:
3294 // For the purpose of ranking implicit conversion sequences as
3295 // described in 13.3.3.2, the ambiguous conversion sequence is
3296 // treated as a user-defined sequence that is indistinguishable
3297 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003298
3299 // String literal to 'char *' conversion has been deprecated in C++03. It has
3300 // been removed from C++11. We still accept this conversion, if it happens at
3301 // the best viable function. Otherwise, this conversion is considered worse
3302 // than ellipsis conversion. Consider this as an extension; this is not in the
3303 // standard. For example:
3304 //
3305 // int &f(...); // #1
3306 // void f(char*); // #2
3307 // void g() { int &r = f("foo"); }
3308 //
3309 // In C++03, we pick #2 as the best viable function.
3310 // In C++11, we pick #1 as the best viable function, because ellipsis
3311 // conversion is better than string-literal to char* conversion (since there
3312 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3313 // convert arguments, #2 would be the best viable function in C++11.
3314 // If the best viable function has this conversion, a warning will be issued
3315 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3316
3317 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3318 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3319 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3320 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3321 ? ImplicitConversionSequence::Worse
3322 : ImplicitConversionSequence::Better;
3323
Douglas Gregor5ab11652010-04-17 22:01:05 +00003324 if (ICS1.getKindRank() < ICS2.getKindRank())
3325 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003326 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003327 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003328
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003329 // The following checks require both conversion sequences to be of
3330 // the same kind.
3331 if (ICS1.getKind() != ICS2.getKind())
3332 return ImplicitConversionSequence::Indistinguishable;
3333
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003334 ImplicitConversionSequence::CompareKind Result =
3335 ImplicitConversionSequence::Indistinguishable;
3336
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003337 // Two implicit conversion sequences of the same form are
3338 // indistinguishable conversion sequences unless one of the
3339 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003340
3341 // List-initialization sequence L1 is a better conversion sequence than
3342 // list-initialization sequence L2 if:
3343 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3344 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003345 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003346 // and N1 is smaller than N2.,
3347 // even if one of the other rules in this paragraph would otherwise apply.
3348 if (!ICS1.isBad()) {
3349 if (ICS1.isStdInitializerListElement() &&
3350 !ICS2.isStdInitializerListElement())
3351 return ImplicitConversionSequence::Better;
3352 if (!ICS1.isStdInitializerListElement() &&
3353 ICS2.isStdInitializerListElement())
3354 return ImplicitConversionSequence::Worse;
3355 }
3356
John McCall0d1da222010-01-12 00:44:57 +00003357 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003358 // Standard conversion sequence S1 is a better conversion sequence than
3359 // standard conversion sequence S2 if [...]
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003360 Result = CompareStandardConversionSequences(S,
3361 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003362 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003363 // User-defined conversion sequence U1 is a better conversion
3364 // sequence than another user-defined conversion sequence U2 if
3365 // they contain the same user-defined conversion function or
3366 // constructor and if the second standard conversion sequence of
3367 // U1 is better than the second standard conversion sequence of
3368 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003369 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003370 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003371 Result = CompareStandardConversionSequences(S,
3372 ICS1.UserDefined.After,
3373 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003374 else
3375 Result = compareConversionFunctions(S,
3376 ICS1.UserDefined.ConversionFunction,
3377 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003378 }
3379
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003380 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003381}
3382
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003383static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3384 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3385 Qualifiers Quals;
3386 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003387 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003389
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003390 return Context.hasSameUnqualifiedType(T1, T2);
3391}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003393// Per 13.3.3.2p3, compare the given standard conversion sequences to
3394// determine if one is a proper subset of the other.
3395static ImplicitConversionSequence::CompareKind
3396compareStandardConversionSubsets(ASTContext &Context,
3397 const StandardConversionSequence& SCS1,
3398 const StandardConversionSequence& SCS2) {
3399 ImplicitConversionSequence::CompareKind Result
3400 = ImplicitConversionSequence::Indistinguishable;
3401
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003403 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003404 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3405 return ImplicitConversionSequence::Better;
3406 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3407 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003409 if (SCS1.Second != SCS2.Second) {
3410 if (SCS1.Second == ICK_Identity)
3411 Result = ImplicitConversionSequence::Better;
3412 else if (SCS2.Second == ICK_Identity)
3413 Result = ImplicitConversionSequence::Worse;
3414 else
3415 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003416 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003417 return ImplicitConversionSequence::Indistinguishable;
3418
3419 if (SCS1.Third == SCS2.Third) {
3420 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3421 : ImplicitConversionSequence::Indistinguishable;
3422 }
3423
3424 if (SCS1.Third == ICK_Identity)
3425 return Result == ImplicitConversionSequence::Worse
3426 ? ImplicitConversionSequence::Indistinguishable
3427 : ImplicitConversionSequence::Better;
3428
3429 if (SCS2.Third == ICK_Identity)
3430 return Result == ImplicitConversionSequence::Better
3431 ? ImplicitConversionSequence::Indistinguishable
3432 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003433
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003434 return ImplicitConversionSequence::Indistinguishable;
3435}
3436
Douglas Gregore696ebb2011-01-26 14:52:12 +00003437/// \brief Determine whether one of the given reference bindings is better
3438/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003439static bool
3440isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3441 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003442 // C++0x [over.ics.rank]p3b4:
3443 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3444 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003445 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003446 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003447 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003448 // reference*.
3449 //
3450 // FIXME: Rvalue references. We're going rogue with the above edits,
3451 // because the semantics in the current C++0x working paper (N3225 at the
3452 // time of this writing) break the standard definition of std::forward
3453 // and std::reference_wrapper when dealing with references to functions.
3454 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003455 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3456 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3457 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003458
Douglas Gregore696ebb2011-01-26 14:52:12 +00003459 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3460 SCS2.IsLvalueReference) ||
3461 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003462 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003463}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003464
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003465/// CompareStandardConversionSequences - Compare two standard
3466/// conversion sequences to determine whether one is better than the
3467/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003468static ImplicitConversionSequence::CompareKind
3469CompareStandardConversionSequences(Sema &S,
3470 const StandardConversionSequence& SCS1,
3471 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003472{
3473 // Standard conversion sequence S1 is a better conversion sequence
3474 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3475
3476 // -- S1 is a proper subsequence of S2 (comparing the conversion
3477 // sequences in the canonical form defined by 13.3.3.1.1,
3478 // excluding any Lvalue Transformation; the identity conversion
3479 // sequence is considered to be a subsequence of any
3480 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003481 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003482 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003483 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003484
3485 // -- the rank of S1 is better than the rank of S2 (by the rules
3486 // defined below), or, if not that,
3487 ImplicitConversionRank Rank1 = SCS1.getRank();
3488 ImplicitConversionRank Rank2 = SCS2.getRank();
3489 if (Rank1 < Rank2)
3490 return ImplicitConversionSequence::Better;
3491 else if (Rank2 < Rank1)
3492 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003493
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003494 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3495 // are indistinguishable unless one of the following rules
3496 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003497
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003498 // A conversion that is not a conversion of a pointer, or
3499 // pointer to member, to bool is better than another conversion
3500 // that is such a conversion.
3501 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3502 return SCS2.isPointerConversionToBool()
3503 ? ImplicitConversionSequence::Better
3504 : ImplicitConversionSequence::Worse;
3505
Douglas Gregor5c407d92008-10-23 00:40:37 +00003506 // C++ [over.ics.rank]p4b2:
3507 //
3508 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003509 // conversion of B* to A* is better than conversion of B* to
3510 // void*, and conversion of A* to void* is better than conversion
3511 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003512 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003513 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003514 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003515 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003516 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3517 // Exactly one of the conversion sequences is a conversion to
3518 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003519 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3520 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003521 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3522 // Neither conversion sequence converts to a void pointer; compare
3523 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003524 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003525 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003526 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003527 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3528 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003529 // Both conversion sequences are conversions to void
3530 // pointers. Compare the source types to determine if there's an
3531 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003532 QualType FromType1 = SCS1.getFromType();
3533 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003534
3535 // Adjust the types we're converting from via the array-to-pointer
3536 // conversion, if we need to.
3537 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003538 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003539 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003540 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003541
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003542 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3543 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003544
John McCall5c32be02010-08-24 20:38:10 +00003545 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003546 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003547 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003548 return ImplicitConversionSequence::Worse;
3549
3550 // Objective-C++: If one interface is more specific than the
3551 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003552 const ObjCObjectPointerType* FromObjCPtr1
3553 = FromType1->getAs<ObjCObjectPointerType>();
3554 const ObjCObjectPointerType* FromObjCPtr2
3555 = FromType2->getAs<ObjCObjectPointerType>();
3556 if (FromObjCPtr1 && FromObjCPtr2) {
3557 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3558 FromObjCPtr2);
3559 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3560 FromObjCPtr1);
3561 if (AssignLeft != AssignRight) {
3562 return AssignLeft? ImplicitConversionSequence::Better
3563 : ImplicitConversionSequence::Worse;
3564 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003565 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003566 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003567
3568 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3569 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003570 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003571 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003572 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003573
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003574 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003575 // Check for a better reference binding based on the kind of bindings.
3576 if (isBetterReferenceBindingKind(SCS1, SCS2))
3577 return ImplicitConversionSequence::Better;
3578 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3579 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003580
Sebastian Redlb28b4072009-03-22 23:49:27 +00003581 // C++ [over.ics.rank]p3b4:
3582 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3583 // which the references refer are the same type except for
3584 // top-level cv-qualifiers, and the type to which the reference
3585 // initialized by S2 refers is more cv-qualified than the type
3586 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003587 QualType T1 = SCS1.getToType(2);
3588 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003589 T1 = S.Context.getCanonicalType(T1);
3590 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003591 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003592 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3593 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003594 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003595 // Objective-C++ ARC: If the references refer to objects with different
3596 // lifetimes, prefer bindings that don't change lifetime.
3597 if (SCS1.ObjCLifetimeConversionBinding !=
3598 SCS2.ObjCLifetimeConversionBinding) {
3599 return SCS1.ObjCLifetimeConversionBinding
3600 ? ImplicitConversionSequence::Worse
3601 : ImplicitConversionSequence::Better;
3602 }
3603
Chandler Carruth8e543b32010-12-12 08:17:55 +00003604 // If the type is an array type, promote the element qualifiers to the
3605 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003606 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003607 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003608 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003609 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003610 if (T2.isMoreQualifiedThan(T1))
3611 return ImplicitConversionSequence::Better;
3612 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003613 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003614 }
3615 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003616
Francois Pichet08d2fa02011-09-18 21:37:37 +00003617 // In Microsoft mode, prefer an integral conversion to a
3618 // floating-to-integral conversion if the integral conversion
3619 // is between types of the same size.
3620 // For example:
3621 // void f(float);
3622 // void f(int);
3623 // int main {
3624 // long a;
3625 // f(a);
3626 // }
3627 // Here, MSVC will call f(int) instead of generating a compile error
3628 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003629 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3630 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003631 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003632 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003633 return ImplicitConversionSequence::Better;
3634
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003635 return ImplicitConversionSequence::Indistinguishable;
3636}
3637
3638/// CompareQualificationConversions - Compares two standard conversion
3639/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003640/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003641static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003642CompareQualificationConversions(Sema &S,
3643 const StandardConversionSequence& SCS1,
3644 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003645 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003646 // -- S1 and S2 differ only in their qualification conversion and
3647 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3648 // cv-qualification signature of type T1 is a proper subset of
3649 // the cv-qualification signature of type T2, and S1 is not the
3650 // deprecated string literal array-to-pointer conversion (4.2).
3651 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3652 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3653 return ImplicitConversionSequence::Indistinguishable;
3654
3655 // FIXME: the example in the standard doesn't use a qualification
3656 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003657 QualType T1 = SCS1.getToType(2);
3658 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003659 T1 = S.Context.getCanonicalType(T1);
3660 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003661 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003662 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3663 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003664
3665 // If the types are the same, we won't learn anything by unwrapped
3666 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003667 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003668 return ImplicitConversionSequence::Indistinguishable;
3669
Chandler Carruth607f38e2009-12-29 07:16:59 +00003670 // If the type is an array type, promote the element qualifiers to the type
3671 // for comparison.
3672 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003673 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003674 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003675 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003676
Mike Stump11289f42009-09-09 15:08:12 +00003677 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003678 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003679
3680 // Objective-C++ ARC:
3681 // Prefer qualification conversions not involving a change in lifetime
3682 // to qualification conversions that do not change lifetime.
3683 if (SCS1.QualificationIncludesObjCLifetime !=
3684 SCS2.QualificationIncludesObjCLifetime) {
3685 Result = SCS1.QualificationIncludesObjCLifetime
3686 ? ImplicitConversionSequence::Worse
3687 : ImplicitConversionSequence::Better;
3688 }
3689
John McCall5c32be02010-08-24 20:38:10 +00003690 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003691 // Within each iteration of the loop, we check the qualifiers to
3692 // determine if this still looks like a qualification
3693 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003694 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003695 // until there are no more pointers or pointers-to-members left
3696 // to unwrap. This essentially mimics what
3697 // IsQualificationConversion does, but here we're checking for a
3698 // strict subset of qualifiers.
3699 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3700 // The qualifiers are the same, so this doesn't tell us anything
3701 // about how the sequences rank.
3702 ;
3703 else if (T2.isMoreQualifiedThan(T1)) {
3704 // T1 has fewer qualifiers, so it could be the better sequence.
3705 if (Result == ImplicitConversionSequence::Worse)
3706 // Neither has qualifiers that are a subset of the other's
3707 // qualifiers.
3708 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003709
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003710 Result = ImplicitConversionSequence::Better;
3711 } else if (T1.isMoreQualifiedThan(T2)) {
3712 // T2 has fewer qualifiers, so it could be the better sequence.
3713 if (Result == ImplicitConversionSequence::Better)
3714 // Neither has qualifiers that are a subset of the other's
3715 // qualifiers.
3716 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003717
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003718 Result = ImplicitConversionSequence::Worse;
3719 } else {
3720 // Qualifiers are disjoint.
3721 return ImplicitConversionSequence::Indistinguishable;
3722 }
3723
3724 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003725 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003726 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003727 }
3728
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003729 // Check that the winning standard conversion sequence isn't using
3730 // the deprecated string literal array to pointer conversion.
3731 switch (Result) {
3732 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003733 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003734 Result = ImplicitConversionSequence::Indistinguishable;
3735 break;
3736
3737 case ImplicitConversionSequence::Indistinguishable:
3738 break;
3739
3740 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003741 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003742 Result = ImplicitConversionSequence::Indistinguishable;
3743 break;
3744 }
3745
3746 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003747}
3748
Douglas Gregor5c407d92008-10-23 00:40:37 +00003749/// CompareDerivedToBaseConversions - Compares two standard conversion
3750/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003751/// various kinds of derived-to-base conversions (C++
3752/// [over.ics.rank]p4b3). As part of these checks, we also look at
3753/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003754static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003755CompareDerivedToBaseConversions(Sema &S,
3756 const StandardConversionSequence& SCS1,
3757 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003758 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003759 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003760 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003761 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003762
3763 // Adjust the types we're converting from via the array-to-pointer
3764 // conversion, if we need to.
3765 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003766 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003767 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003768 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003769
3770 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003771 FromType1 = S.Context.getCanonicalType(FromType1);
3772 ToType1 = S.Context.getCanonicalType(ToType1);
3773 FromType2 = S.Context.getCanonicalType(FromType2);
3774 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003775
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003776 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003777 //
3778 // If class B is derived directly or indirectly from class A and
3779 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003780 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003781 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003782 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003783 SCS2.Second == ICK_Pointer_Conversion &&
3784 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3785 FromType1->isPointerType() && FromType2->isPointerType() &&
3786 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003787 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003788 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003789 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003790 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003791 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003792 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003793 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003794 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003795
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003796 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003797 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003798 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003799 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003800 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003801 return ImplicitConversionSequence::Worse;
3802 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003803
3804 // -- conversion of B* to A* is better than conversion of C* to A*,
3805 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003806 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003807 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003808 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003809 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003810 }
3811 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3812 SCS2.Second == ICK_Pointer_Conversion) {
3813 const ObjCObjectPointerType *FromPtr1
3814 = FromType1->getAs<ObjCObjectPointerType>();
3815 const ObjCObjectPointerType *FromPtr2
3816 = FromType2->getAs<ObjCObjectPointerType>();
3817 const ObjCObjectPointerType *ToPtr1
3818 = ToType1->getAs<ObjCObjectPointerType>();
3819 const ObjCObjectPointerType *ToPtr2
3820 = ToType2->getAs<ObjCObjectPointerType>();
3821
3822 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3823 // Apply the same conversion ranking rules for Objective-C pointer types
3824 // that we do for C++ pointers to class types. However, we employ the
3825 // Objective-C pseudo-subtyping relationship used for assignment of
3826 // Objective-C pointer types.
3827 bool FromAssignLeft
3828 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3829 bool FromAssignRight
3830 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3831 bool ToAssignLeft
3832 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3833 bool ToAssignRight
3834 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3835
3836 // A conversion to an a non-id object pointer type or qualified 'id'
3837 // type is better than a conversion to 'id'.
3838 if (ToPtr1->isObjCIdType() &&
3839 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3840 return ImplicitConversionSequence::Worse;
3841 if (ToPtr2->isObjCIdType() &&
3842 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3843 return ImplicitConversionSequence::Better;
3844
3845 // A conversion to a non-id object pointer type is better than a
3846 // conversion to a qualified 'id' type
3847 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3848 return ImplicitConversionSequence::Worse;
3849 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3850 return ImplicitConversionSequence::Better;
3851
3852 // A conversion to an a non-Class object pointer type or qualified 'Class'
3853 // type is better than a conversion to 'Class'.
3854 if (ToPtr1->isObjCClassType() &&
3855 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3856 return ImplicitConversionSequence::Worse;
3857 if (ToPtr2->isObjCClassType() &&
3858 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3859 return ImplicitConversionSequence::Better;
3860
3861 // A conversion to a non-Class object pointer type is better than a
3862 // conversion to a qualified 'Class' type.
3863 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3864 return ImplicitConversionSequence::Worse;
3865 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3866 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003867
Douglas Gregor058d3de2011-01-31 18:51:41 +00003868 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3869 if (S.Context.hasSameType(FromType1, FromType2) &&
3870 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3871 (ToAssignLeft != ToAssignRight))
3872 return ToAssignLeft? ImplicitConversionSequence::Worse
3873 : ImplicitConversionSequence::Better;
3874
3875 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3876 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3877 (FromAssignLeft != FromAssignRight))
3878 return FromAssignLeft? ImplicitConversionSequence::Better
3879 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003880 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003881 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003882
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003883 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003884 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3885 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3886 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003887 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003888 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003889 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003890 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003891 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003892 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003894 ToType2->getAs<MemberPointerType>();
3895 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3896 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3897 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3898 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3899 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3900 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3901 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3902 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003903 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003904 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003905 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003906 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003907 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003908 return ImplicitConversionSequence::Better;
3909 }
3910 // conversion of B::* to C::* is better than conversion of A::* to C::*
3911 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003912 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003913 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003914 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003915 return ImplicitConversionSequence::Worse;
3916 }
3917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003918
Douglas Gregor5ab11652010-04-17 22:01:05 +00003919 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003920 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003921 // -- binding of an expression of type C to a reference of type
3922 // B& is better than binding an expression of type C to a
3923 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003924 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3925 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3926 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003927 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003928 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003929 return ImplicitConversionSequence::Worse;
3930 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003931
Douglas Gregor2fe98832008-11-03 19:09:14 +00003932 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003933 // -- binding of an expression of type B to a reference of type
3934 // A& is better than binding an expression of type C to a
3935 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003936 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3937 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3938 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003939 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003940 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003941 return ImplicitConversionSequence::Worse;
3942 }
3943 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003944
Douglas Gregor5c407d92008-10-23 00:40:37 +00003945 return ImplicitConversionSequence::Indistinguishable;
3946}
3947
Douglas Gregor45bb4832013-03-26 23:36:30 +00003948/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3949/// C++ class.
3950static bool isTypeValid(QualType T) {
3951 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3952 return !Record->isInvalidDecl();
3953
3954 return true;
3955}
3956
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003957/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3958/// determine whether they are reference-related,
3959/// reference-compatible, reference-compatible with added
3960/// qualification, or incompatible, for use in C++ initialization by
3961/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3962/// type, and the first type (T1) is the pointee type of the reference
3963/// type being initialized.
3964Sema::ReferenceCompareResult
3965Sema::CompareReferenceRelationship(SourceLocation Loc,
3966 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003967 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003968 bool &ObjCConversion,
3969 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003970 assert(!OrigT1->isReferenceType() &&
3971 "T1 must be the pointee type of the reference type");
3972 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3973
3974 QualType T1 = Context.getCanonicalType(OrigT1);
3975 QualType T2 = Context.getCanonicalType(OrigT2);
3976 Qualifiers T1Quals, T2Quals;
3977 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3978 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3979
3980 // C++ [dcl.init.ref]p4:
3981 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3982 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3983 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003984 DerivedToBase = false;
3985 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003986 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003987 if (UnqualT1 == UnqualT2) {
3988 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003989 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00003990 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3991 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003992 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003993 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3994 UnqualT2->isObjCObjectOrInterfaceType() &&
3995 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3996 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003997 else
3998 return Ref_Incompatible;
3999
4000 // At this point, we know that T1 and T2 are reference-related (at
4001 // least).
4002
4003 // If the type is an array type, promote the element qualifiers to the type
4004 // for comparison.
4005 if (isa<ArrayType>(T1) && T1Quals)
4006 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4007 if (isa<ArrayType>(T2) && T2Quals)
4008 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4009
4010 // C++ [dcl.init.ref]p4:
4011 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4012 // reference-related to T2 and cv1 is the same cv-qualification
4013 // as, or greater cv-qualification than, cv2. For purposes of
4014 // overload resolution, cases for which cv1 is greater
4015 // cv-qualification than cv2 are identified as
4016 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004017 //
4018 // Note that we also require equivalence of Objective-C GC and address-space
4019 // qualifiers when performing these computations, so that e.g., an int in
4020 // address space 1 is not reference-compatible with an int in address
4021 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004022 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4023 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004024 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4025 ObjCLifetimeConversion = true;
4026
John McCall31168b02011-06-15 23:02:42 +00004027 T1Quals.removeObjCLifetime();
4028 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004029 }
4030
Douglas Gregord517d552011-04-28 17:56:11 +00004031 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004032 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004033 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004034 return Ref_Compatible_With_Added_Qualification;
4035 else
4036 return Ref_Related;
4037}
4038
Douglas Gregor836a7e82010-08-11 02:15:33 +00004039/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004040/// with DeclType. Return true if something definite is found.
4041static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004042FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4043 QualType DeclType, SourceLocation DeclLoc,
4044 Expr *Init, QualType T2, bool AllowRvalues,
4045 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004046 assert(T2->isRecordType() && "Can only find conversions of record types.");
4047 CXXRecordDecl *T2RecordDecl
4048 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4049
Richard Smith100b24a2014-04-17 01:52:14 +00004050 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004051 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4052 for (auto I = Conversions.begin(), E = Conversions.end(); 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:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004504 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004505 // 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;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005402 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005403 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005404
Larisse Voufo236bec22013-06-10 06:50:24 +00005405 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005406 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005407
Larisse Voufo236bec22013-06-10 06:50:24 +00005408 // To check that there is only one target type, in C++1y:
5409 QualType ToType;
5410 bool HasUniqueTargetType = true;
5411
5412 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005413 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005414 NamedDecl *D = (*I)->getUnderlyingDecl();
5415 CXXConversionDecl *Conversion;
5416 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5417 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005418 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005419 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5420 else
5421 continue; // C++11 does not consider conversion operator templates(?).
5422 } else
5423 Conversion = cast<CXXConversionDecl>(D);
5424
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005425 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005426 "Conversion operator templates are considered potentially "
5427 "viable in C++1y");
5428
5429 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5430 if (Converter.match(CurToType) || ConvTemplate) {
5431
5432 if (Conversion->isExplicit()) {
5433 // FIXME: For C++1y, do we need this restriction?
5434 // cf. diagnoseNoViableConversion()
5435 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005436 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005437 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005438 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005439 if (ToType.isNull())
5440 ToType = CurToType.getUnqualifiedType();
5441 else if (HasUniqueTargetType &&
5442 (CurToType.getUnqualifiedType() != ToType))
5443 HasUniqueTargetType = false;
5444 }
5445 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005446 }
Richard Smith8dd34252012-02-04 07:07:42 +00005447 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005448 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005449
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005450 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005451 // C++1y [conv]p6:
5452 // ... An expression e of class type E appearing in such a context
5453 // is said to be contextually implicitly converted to a specified
5454 // type T and is well-formed if and only if e can be implicitly
5455 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005456 // for conversion functions whose return type is cv T or reference to
5457 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005458 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005459
Larisse Voufo236bec22013-06-10 06:50:24 +00005460 // If no unique T is found:
5461 if (ToType.isNull()) {
5462 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5463 HadMultipleCandidates,
5464 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005465 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005466 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005468
Larisse Voufo236bec22013-06-10 06:50:24 +00005469 // If more than one unique Ts are found:
5470 if (!HasUniqueTargetType)
5471 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5472 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005473
Larisse Voufo236bec22013-06-10 06:50:24 +00005474 // If one unique T is found:
5475 // First, build a candidate set from the previously recorded
5476 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005477 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005478 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5479 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005480
Larisse Voufo236bec22013-06-10 06:50:24 +00005481 // Then, perform overload resolution over the candidate set.
5482 OverloadCandidateSet::iterator Best;
5483 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5484 case OR_Success: {
5485 // Apply this conversion.
5486 DeclAccessPair Found =
5487 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5488 if (recordConversion(*this, Loc, From, Converter, T,
5489 HadMultipleCandidates, Found))
5490 return ExprError();
5491 break;
5492 }
5493 case OR_Ambiguous:
5494 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5495 ViableConversions);
5496 case OR_No_Viable_Function:
5497 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5498 HadMultipleCandidates,
5499 ExplicitConversions))
5500 return ExprError();
5501 // fall through 'OR_Deleted' case.
5502 case OR_Deleted:
5503 // We'll complain below about a non-integral condition type.
5504 break;
5505 }
5506 } else {
5507 switch (ViableConversions.size()) {
5508 case 0: {
5509 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5510 HadMultipleCandidates,
5511 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005512 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005513
Larisse Voufo236bec22013-06-10 06:50:24 +00005514 // We'll complain below about a non-integral condition type.
5515 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005516 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005517 case 1: {
5518 // Apply this conversion.
5519 DeclAccessPair Found = ViableConversions[0];
5520 if (recordConversion(*this, Loc, From, Converter, T,
5521 HadMultipleCandidates, Found))
5522 return ExprError();
5523 break;
5524 }
5525 default:
5526 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5527 ViableConversions);
5528 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005529 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005530
Larisse Voufo236bec22013-06-10 06:50:24 +00005531 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005532}
5533
Richard Smith100b24a2014-04-17 01:52:14 +00005534/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5535/// an acceptable non-member overloaded operator for a call whose
5536/// arguments have types T1 (and, if non-empty, T2). This routine
5537/// implements the check in C++ [over.match.oper]p3b2 concerning
5538/// enumeration types.
5539static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5540 FunctionDecl *Fn,
5541 ArrayRef<Expr *> Args) {
5542 QualType T1 = Args[0]->getType();
5543 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5544
5545 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5546 return true;
5547
5548 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5549 return true;
5550
5551 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5552 if (Proto->getNumParams() < 1)
5553 return false;
5554
5555 if (T1->isEnumeralType()) {
5556 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5557 if (Context.hasSameUnqualifiedType(T1, ArgType))
5558 return true;
5559 }
5560
5561 if (Proto->getNumParams() < 2)
5562 return false;
5563
5564 if (!T2.isNull() && T2->isEnumeralType()) {
5565 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5566 if (Context.hasSameUnqualifiedType(T2, ArgType))
5567 return true;
5568 }
5569
5570 return false;
5571}
5572
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005573/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005574/// candidate functions, using the given function call arguments. If
5575/// @p SuppressUserConversions, then don't allow user-defined
5576/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005577///
James Dennett2a4d13c2012-06-15 07:13:21 +00005578/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005579/// based on an incomplete set of function arguments. This feature is used by
5580/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005581void
5582Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005583 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005584 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005585 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005586 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005587 bool PartialOverloading,
5588 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005589 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005590 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005591 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005592 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005593 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005594
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005595 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005596 if (!isa<CXXConstructorDecl>(Method)) {
5597 // If we get here, it's because we're calling a member function
5598 // that is named without a member access expression (e.g.,
5599 // "this->f") that was either written explicitly or created
5600 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005601 // function, e.g., X::f(). We use an empty type for the implied
5602 // object argument (C++ [over.call.func]p3), and the acting context
5603 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005604 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005605 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005606 Args, CandidateSet, SuppressUserConversions,
5607 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005608 return;
5609 }
5610 // We treat a constructor like a non-member function, since its object
5611 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005612 }
5613
Douglas Gregorff7028a2009-11-13 23:59:09 +00005614 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005615 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005616
Richard Smith100b24a2014-04-17 01:52:14 +00005617 // C++ [over.match.oper]p3:
5618 // if no operand has a class type, only those non-member functions in the
5619 // lookup set that have a first parameter of type T1 or "reference to
5620 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5621 // is a right operand) a second parameter of type T2 or "reference to
5622 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5623 // candidate functions.
5624 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5625 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5626 return;
5627
Richard Smith8b86f2d2013-11-04 01:48:18 +00005628 // C++11 [class.copy]p11: [DR1402]
5629 // A defaulted move constructor that is defined as deleted is ignored by
5630 // overload resolution.
5631 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5632 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5633 Constructor->isMoveConstructor())
5634 return;
5635
Douglas Gregor27381f32009-11-23 12:27:39 +00005636 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005637 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005638
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005639 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005640 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005641 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005642 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005643 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005644 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005645 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005646 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005647
John McCall578a1f82014-12-14 01:46:53 +00005648 if (Constructor) {
5649 // C++ [class.copy]p3:
5650 // A member function template is never instantiated to perform the copy
5651 // of a class object to an object of its class type.
5652 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5653 if (Args.size() == 1 &&
5654 Constructor->isSpecializationCopyingObject() &&
5655 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5656 IsDerivedFrom(Args[0]->getType(), ClassType))) {
5657 Candidate.Viable = false;
5658 Candidate.FailureKind = ovl_fail_illegal_constructor;
5659 return;
5660 }
5661 }
5662
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005663 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005664
5665 // (C++ 13.3.2p2): A candidate function having fewer than m
5666 // parameters is viable only if it has an ellipsis in its parameter
5667 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005668 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005669 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005670 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005671 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005672 return;
5673 }
5674
5675 // (C++ 13.3.2p2): A candidate function having more than m parameters
5676 // is viable only if the (m+1)st parameter has a default argument
5677 // (8.3.6). For the purposes of overload resolution, the
5678 // parameter list is truncated on the right, so that there are
5679 // exactly m parameters.
5680 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005681 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005682 // Not enough arguments.
5683 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005684 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005685 return;
5686 }
5687
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005688 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005689 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005690 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005691 // Skip the check for callers that are implicit members, because in this
5692 // case we may not yet know what the member's target is; the target is
5693 // inferred for the member automatically, based on the bases and fields of
5694 // the class.
5695 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005696 Candidate.Viable = false;
5697 Candidate.FailureKind = ovl_fail_bad_target;
5698 return;
5699 }
5700
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005701 // Determine the implicit conversion sequences for each of the
5702 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005703 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005704 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005705 // (C++ 13.3.2p3): for F to be a viable function, there shall
5706 // exist for each argument an implicit conversion sequence
5707 // (13.3.3.1) that converts that argument to the corresponding
5708 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005709 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005710 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005711 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005712 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005713 /*InOverloadResolution=*/true,
5714 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005715 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005716 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005717 if (Candidate.Conversions[ArgIdx].isBad()) {
5718 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005719 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005720 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005721 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005722 } else {
5723 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5724 // argument for which there is no corresponding parameter is
5725 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005726 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005727 }
5728 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005729
5730 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5731 Candidate.Viable = false;
5732 Candidate.FailureKind = ovl_fail_enable_if;
5733 Candidate.DeductionFailure.Data = FailedAttr;
5734 return;
5735 }
5736}
5737
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005738ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005739 bool IsInstance) {
5740 SmallVector<ObjCMethodDecl*, 4> Methods;
5741 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5742 return nullptr;
5743
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005744 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5745 bool Match = true;
5746 ObjCMethodDecl *Method = Methods[b];
5747 unsigned NumNamedArgs = Sel.getNumArgs();
5748 // Method might have more arguments than selector indicates. This is due
5749 // to addition of c-style arguments in method.
5750 if (Method->param_size() > NumNamedArgs)
5751 NumNamedArgs = Method->param_size();
5752 if (Args.size() < NumNamedArgs)
5753 continue;
5754
5755 for (unsigned i = 0; i < NumNamedArgs; i++) {
5756 // We can't do any type-checking on a type-dependent argument.
5757 if (Args[i]->isTypeDependent()) {
5758 Match = false;
5759 break;
5760 }
5761
5762 ParmVarDecl *param = Method->parameters()[i];
5763 Expr *argExpr = Args[i];
5764 assert(argExpr && "SelectBestMethod(): missing expression");
5765
5766 // Strip the unbridged-cast placeholder expression off unless it's
5767 // a consumed argument.
5768 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5769 !param->hasAttr<CFConsumedAttr>())
5770 argExpr = stripARCUnbridgedCast(argExpr);
5771
5772 // If the parameter is __unknown_anytype, move on to the next method.
5773 if (param->getType() == Context.UnknownAnyTy) {
5774 Match = false;
5775 break;
5776 }
5777
5778 ImplicitConversionSequence ConversionState
5779 = TryCopyInitialization(*this, argExpr, param->getType(),
5780 /*SuppressUserConversions*/false,
5781 /*InOverloadResolution=*/true,
5782 /*AllowObjCWritebackConversion=*/
5783 getLangOpts().ObjCAutoRefCount,
5784 /*AllowExplicit*/false);
5785 if (ConversionState.isBad()) {
5786 Match = false;
5787 break;
5788 }
5789 }
5790 // Promote additional arguments to variadic methods.
5791 if (Match && Method->isVariadic()) {
5792 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5793 if (Args[i]->isTypeDependent()) {
5794 Match = false;
5795 break;
5796 }
5797 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5798 nullptr);
5799 if (Arg.isInvalid()) {
5800 Match = false;
5801 break;
5802 }
5803 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005804 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005805 // Check for extra arguments to non-variadic methods.
5806 if (Args.size() != NumNamedArgs)
5807 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005808 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5809 // Special case when selectors have no argument. In this case, select
5810 // one with the most general result type of 'id'.
5811 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5812 QualType ReturnT = Methods[b]->getReturnType();
5813 if (ReturnT->isObjCIdType())
5814 return Methods[b];
5815 }
5816 }
5817 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005818
5819 if (Match)
5820 return Method;
5821 }
5822 return nullptr;
5823}
5824
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005825static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5826
5827EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5828 bool MissingImplicitThis) {
5829 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5830 // we need to find the first failing one.
5831 if (!Function->hasAttrs())
Craig Topperc3ec1492014-05-26 06:22:03 +00005832 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005833 AttrVec Attrs = Function->getAttrs();
5834 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5835 IsNotEnableIfAttr);
5836 if (Attrs.begin() == E)
Craig Topperc3ec1492014-05-26 06:22:03 +00005837 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005838 std::reverse(Attrs.begin(), E);
5839
5840 SFINAETrap Trap(*this);
5841
5842 // Convert the arguments.
5843 SmallVector<Expr *, 16> ConvertedArgs;
5844 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005845 bool ContainsValueDependentExpr = false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005846 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5847 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005848 !cast<CXXMethodDecl>(Function)->isStatic() &&
5849 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005850 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5851 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005852 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005853 Method, Method);
5854 if (R.isInvalid()) {
5855 InitializationFailed = true;
5856 break;
5857 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005858 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005859 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005860 } else {
5861 ExprResult R =
5862 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5863 Context,
5864 Function->getParamDecl(i)),
5865 SourceLocation(),
5866 Args[i]);
5867 if (R.isInvalid()) {
5868 InitializationFailed = true;
5869 break;
5870 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005871 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005872 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005873 }
5874 }
5875
5876 if (InitializationFailed || Trap.hasErrorOccurred())
5877 return cast<EnableIfAttr>(Attrs[0]);
5878
5879 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5880 APValue Result;
5881 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005882 if (EIA->getCond()->isValueDependent()) {
5883 // Don't even try now, we'll examine it after instantiation.
5884 continue;
5885 }
5886
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005887 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005888 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5889 if (!ContainsValueDependentExpr)
5890 return EIA;
5891 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005892 return EIA;
5893 }
5894 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005895 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005896}
5897
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005898/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005899/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005900void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005901 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005902 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005903 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005904 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005905 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00005906 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005907 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5908 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005909 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005910 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005911 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005912 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005913 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005914 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005915 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005916 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005917 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005918 } else {
John McCalla0296f72010-03-19 07:35:19 +00005919 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005920 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5921 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005922 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005923 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005924 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005925 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005926 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005927 CandidateSet, SuppressUserConversions,
5928 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005929 else
John McCalla0296f72010-03-19 07:35:19 +00005930 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005931 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005932 CandidateSet, SuppressUserConversions,
5933 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005934 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005935 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005936}
5937
John McCallf0f1cf02009-11-17 07:50:12 +00005938/// AddMethodCandidate - Adds a named decl (which is some kind of
5939/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005940void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005941 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005942 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005943 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005944 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005945 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005946 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005947 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005948
5949 if (isa<UsingShadowDecl>(Decl))
5950 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005951
John McCallf0f1cf02009-11-17 07:50:12 +00005952 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5953 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5954 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005955 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00005956 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005957 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005958 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005959 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005960 } else {
John McCalla0296f72010-03-19 07:35:19 +00005961 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005962 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005963 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005964 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005965 }
5966}
5967
Douglas Gregor436424c2008-11-18 23:14:02 +00005968/// AddMethodCandidate - Adds the given C++ member function to the set
5969/// of candidate functions, using the given function call arguments
5970/// and the object argument (@c Object). For example, in a call
5971/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5972/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5973/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005974/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005975void
John McCalla0296f72010-03-19 07:35:19 +00005976Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005977 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005978 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005979 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005980 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005981 bool SuppressUserConversions,
5982 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005983 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005984 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005985 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005986 assert(!isa<CXXConstructorDecl>(Method) &&
5987 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005988
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005989 if (!CandidateSet.isNewCandidate(Method))
5990 return;
5991
Richard Smith8b86f2d2013-11-04 01:48:18 +00005992 // C++11 [class.copy]p23: [DR1402]
5993 // A defaulted move assignment operator that is defined as deleted is
5994 // ignored by overload resolution.
5995 if (Method->isDefaulted() && Method->isDeleted() &&
5996 Method->isMoveAssignmentOperator())
5997 return;
5998
Douglas Gregor27381f32009-11-23 12:27:39 +00005999 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006000 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006001
Douglas Gregor436424c2008-11-18 23:14:02 +00006002 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006003 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006004 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006005 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006006 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006007 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006008 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006009
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006010 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006011
6012 // (C++ 13.3.2p2): A candidate function having fewer than m
6013 // parameters is viable only if it has an ellipsis in its parameter
6014 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006015 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6016 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006017 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006018 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006019 return;
6020 }
6021
6022 // (C++ 13.3.2p2): A candidate function having more than m parameters
6023 // is viable only if the (m+1)st parameter has a default argument
6024 // (8.3.6). For the purposes of overload resolution, the
6025 // parameter list is truncated on the right, so that there are
6026 // exactly m parameters.
6027 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006028 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006029 // Not enough arguments.
6030 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006031 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006032 return;
6033 }
6034
6035 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006036
John McCall6e9f8f62009-12-03 04:06:58 +00006037 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006038 // The implicit object argument is ignored.
6039 Candidate.IgnoreObjectArgument = true;
6040 else {
6041 // Determine the implicit conversion sequence for the object
6042 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00006043 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00006044 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6045 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006046 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006047 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006048 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006049 return;
6050 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006051 }
6052
Eli Bendersky291a57e2014-09-25 23:59:08 +00006053 // (CUDA B.1): Check for invalid calls between targets.
6054 if (getLangOpts().CUDA)
6055 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6056 if (CheckCUDATarget(Caller, Method)) {
6057 Candidate.Viable = false;
6058 Candidate.FailureKind = ovl_fail_bad_target;
6059 return;
6060 }
6061
Douglas Gregor436424c2008-11-18 23:14:02 +00006062 // Determine the implicit conversion sequences for each of the
6063 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006064 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006065 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006066 // (C++ 13.3.2p3): for F to be a viable function, there shall
6067 // exist for each argument an implicit conversion sequence
6068 // (13.3.3.1) that converts that argument to the corresponding
6069 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006070 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006071 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006072 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006073 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006074 /*InOverloadResolution=*/true,
6075 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006076 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006077 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006078 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006079 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006080 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006081 }
6082 } else {
6083 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6084 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006085 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006086 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006087 }
6088 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006089
6090 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6091 Candidate.Viable = false;
6092 Candidate.FailureKind = ovl_fail_enable_if;
6093 Candidate.DeductionFailure.Data = FailedAttr;
6094 return;
6095 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006096}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006097
Douglas Gregor97628d62009-08-21 00:16:32 +00006098/// \brief Add a C++ member function template as a candidate to the candidate
6099/// set, using template argument deduction to produce an appropriate member
6100/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006101void
Douglas Gregor97628d62009-08-21 00:16:32 +00006102Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006103 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006104 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006105 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006106 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006107 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006108 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006109 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006110 bool SuppressUserConversions,
6111 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006112 if (!CandidateSet.isNewCandidate(MethodTmpl))
6113 return;
6114
Douglas Gregor97628d62009-08-21 00:16:32 +00006115 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006116 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006117 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006118 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006119 // candidate functions in the usual way.113) A given name can refer to one
6120 // or more function templates and also to a set of overloaded non-template
6121 // functions. In such a case, the candidate functions generated from each
6122 // function template are combined with the set of non-template candidate
6123 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006124 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006125 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006126 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006127 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006128 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006129 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006130 Candidate.FoundDecl = FoundDecl;
6131 Candidate.Function = MethodTmpl->getTemplatedDecl();
6132 Candidate.Viable = false;
6133 Candidate.FailureKind = ovl_fail_bad_deduction;
6134 Candidate.IsSurrogate = false;
6135 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006136 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006137 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006138 Info);
6139 return;
6140 }
Mike Stump11289f42009-09-09 15:08:12 +00006141
Douglas Gregor97628d62009-08-21 00:16:32 +00006142 // Add the function template specialization produced by template argument
6143 // deduction as a candidate.
6144 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006145 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006146 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006147 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006148 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006149 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006150}
6151
Douglas Gregor05155d82009-08-21 23:19:43 +00006152/// \brief Add a C++ function template specialization as a candidate
6153/// in the candidate set, using template argument deduction to produce
6154/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006155void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006156Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006157 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006158 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006159 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006160 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006161 bool SuppressUserConversions,
6162 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006163 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6164 return;
6165
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006166 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006167 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006168 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006169 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006170 // candidate functions in the usual way.113) A given name can refer to one
6171 // or more function templates and also to a set of overloaded non-template
6172 // functions. In such a case, the candidate functions generated from each
6173 // function template are combined with the set of non-template candidate
6174 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006175 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006176 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006177 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006178 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006179 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006180 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006181 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006182 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6183 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006184 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006185 Candidate.IsSurrogate = false;
6186 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006187 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006188 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006189 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006190 return;
6191 }
Mike Stump11289f42009-09-09 15:08:12 +00006192
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006193 // Add the function template specialization produced by template argument
6194 // deduction as a candidate.
6195 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006196 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006197 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006198}
Mike Stump11289f42009-09-09 15:08:12 +00006199
Douglas Gregor4b60a152013-11-07 22:34:54 +00006200/// Determine whether this is an allowable conversion from the result
6201/// of an explicit conversion operator to the expected type, per C++
6202/// [over.match.conv]p1 and [over.match.ref]p1.
6203///
6204/// \param ConvType The return type of the conversion function.
6205///
6206/// \param ToType The type we are converting to.
6207///
6208/// \param AllowObjCPointerConversion Allow a conversion from one
6209/// Objective-C pointer to another.
6210///
6211/// \returns true if the conversion is allowable, false otherwise.
6212static bool isAllowableExplicitConversion(Sema &S,
6213 QualType ConvType, QualType ToType,
6214 bool AllowObjCPointerConversion) {
6215 QualType ToNonRefType = ToType.getNonReferenceType();
6216
6217 // Easy case: the types are the same.
6218 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6219 return true;
6220
6221 // Allow qualification conversions.
6222 bool ObjCLifetimeConversion;
6223 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6224 ObjCLifetimeConversion))
6225 return true;
6226
6227 // If we're not allowed to consider Objective-C pointer conversions,
6228 // we're done.
6229 if (!AllowObjCPointerConversion)
6230 return false;
6231
6232 // Is this an Objective-C pointer conversion?
6233 bool IncompatibleObjC = false;
6234 QualType ConvertedType;
6235 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6236 IncompatibleObjC);
6237}
6238
Douglas Gregora1f013e2008-11-07 22:36:19 +00006239/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006240/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006241/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006242/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006243/// (which may or may not be the same type as the type that the
6244/// conversion function produces).
6245void
6246Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006247 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006248 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006249 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006250 OverloadCandidateSet& CandidateSet,
6251 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006252 assert(!Conversion->getDescribedFunctionTemplate() &&
6253 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006254 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006255 if (!CandidateSet.isNewCandidate(Conversion))
6256 return;
6257
Richard Smith2a7d4812013-05-04 07:00:32 +00006258 // If the conversion function has an undeduced return type, trigger its
6259 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006260 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006261 if (DeduceReturnType(Conversion, From->getExprLoc()))
6262 return;
6263 ConvType = Conversion->getConversionType().getNonReferenceType();
6264 }
6265
Richard Smith089c3162013-09-21 21:55:46 +00006266 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6267 // operator is only a candidate if its return type is the target type or
6268 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006269 if (Conversion->isExplicit() &&
6270 !isAllowableExplicitConversion(*this, ConvType, ToType,
6271 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006272 return;
6273
Douglas Gregor27381f32009-11-23 12:27:39 +00006274 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006275 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006276
Douglas Gregora1f013e2008-11-07 22:36:19 +00006277 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006278 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006279 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006280 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006281 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006282 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006283 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006284 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006285 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006286 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006287 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006288
Douglas Gregor6affc782010-08-19 15:37:02 +00006289 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006290 // For conversion functions, the function is considered to be a member of
6291 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006292 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006293 //
6294 // Determine the implicit conversion sequence for the implicit
6295 // object parameter.
6296 QualType ImplicitParamType = From->getType();
6297 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6298 ImplicitParamType = FromPtrType->getPointeeType();
6299 CXXRecordDecl *ConversionContext
6300 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006301
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006302 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006303 = TryObjectArgumentInitialization(*this, From->getType(),
6304 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006305 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006306
John McCall0d1da222010-01-12 00:44:57 +00006307 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006308 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006309 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006310 return;
6311 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006312
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006313 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006314 // derived to base as such conversions are given Conversion Rank. They only
6315 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6316 QualType FromCanon
6317 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6318 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6319 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6320 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006321 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006322 return;
6323 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006324
Douglas Gregora1f013e2008-11-07 22:36:19 +00006325 // To determine what the conversion from the result of calling the
6326 // conversion function to the type we're eventually trying to
6327 // convert to (ToType), we need to synthesize a call to the
6328 // conversion function and attempt copy initialization from it. This
6329 // makes sure that we get the right semantics with respect to
6330 // lvalues/rvalues and the type. Fortunately, we can allocate this
6331 // call on the stack and we don't need its arguments to be
6332 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006333 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006334 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006335 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6336 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006337 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006338 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006339
Richard Smith48d24642011-07-13 22:53:21 +00006340 QualType ConversionType = Conversion->getConversionType();
6341 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006342 Candidate.Viable = false;
6343 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6344 return;
6345 }
6346
Richard Smith48d24642011-07-13 22:53:21 +00006347 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006348
Mike Stump11289f42009-09-09 15:08:12 +00006349 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006350 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6351 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006352 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006353 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006354 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006355 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006356 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006357 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006358 /*InOverloadResolution=*/false,
6359 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006360
John McCall0d1da222010-01-12 00:44:57 +00006361 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006362 case ImplicitConversionSequence::StandardConversion:
6363 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006364
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006365 // C++ [over.ics.user]p3:
6366 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006367 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006368 // shall have exact match rank.
6369 if (Conversion->getPrimaryTemplate() &&
6370 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6371 Candidate.Viable = false;
6372 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006373 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006374 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006375
Douglas Gregorcba72b12011-01-21 05:18:22 +00006376 // C++0x [dcl.init.ref]p5:
6377 // In the second case, if the reference is an rvalue reference and
6378 // the second standard conversion sequence of the user-defined
6379 // conversion sequence includes an lvalue-to-rvalue conversion, the
6380 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006381 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006382 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6383 Candidate.Viable = false;
6384 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006385 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006386 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006387 break;
6388
6389 case ImplicitConversionSequence::BadConversion:
6390 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006391 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006392 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006393
6394 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006395 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006396 "Can only end up with a standard conversion sequence or failure");
6397 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006398
Craig Topper5fc8fc22014-08-27 06:28:36 +00006399 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006400 Candidate.Viable = false;
6401 Candidate.FailureKind = ovl_fail_enable_if;
6402 Candidate.DeductionFailure.Data = FailedAttr;
6403 return;
6404 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006405}
6406
Douglas Gregor05155d82009-08-21 23:19:43 +00006407/// \brief Adds a conversion function template specialization
6408/// candidate to the overload set, using template argument deduction
6409/// to deduce the template arguments of the conversion function
6410/// template from the type that we are converting to (C++
6411/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006412void
Douglas Gregor05155d82009-08-21 23:19:43 +00006413Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006414 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006415 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006416 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006417 OverloadCandidateSet &CandidateSet,
6418 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006419 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6420 "Only conversion function templates permitted here");
6421
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006422 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6423 return;
6424
Craig Toppere6706e42012-09-19 02:26:47 +00006425 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006426 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006427 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006428 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006429 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006430 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006431 Candidate.FoundDecl = FoundDecl;
6432 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6433 Candidate.Viable = false;
6434 Candidate.FailureKind = ovl_fail_bad_deduction;
6435 Candidate.IsSurrogate = false;
6436 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006437 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006438 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006439 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006440 return;
6441 }
Mike Stump11289f42009-09-09 15:08:12 +00006442
Douglas Gregor05155d82009-08-21 23:19:43 +00006443 // Add the conversion function template specialization produced by
6444 // template argument deduction as a candidate.
6445 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006446 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006447 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006448}
6449
Douglas Gregorab7897a2008-11-19 22:57:39 +00006450/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6451/// converts the given @c Object to a function pointer via the
6452/// conversion function @c Conversion, and then attempts to call it
6453/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6454/// the type of function that we'll eventually be calling.
6455void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006456 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006457 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006458 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006459 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006460 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006461 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006462 if (!CandidateSet.isNewCandidate(Conversion))
6463 return;
6464
Douglas Gregor27381f32009-11-23 12:27:39 +00006465 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006466 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006467
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006468 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006469 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006470 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006471 Candidate.Surrogate = Conversion;
6472 Candidate.Viable = true;
6473 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006474 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006475 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006476
6477 // Determine the implicit conversion sequence for the implicit
6478 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006479 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006480 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006481 Object->Classify(Context),
6482 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006483 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006484 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006485 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006486 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006487 return;
6488 }
6489
6490 // The first conversion is actually a user-defined conversion whose
6491 // first conversion is ObjectInit's standard conversion (which is
6492 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006493 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006494 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006495 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006496 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006497 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006498 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006499 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006500 = Candidate.Conversions[0].UserDefined.Before;
6501 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6502
Mike Stump11289f42009-09-09 15:08:12 +00006503 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006504 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006505
6506 // (C++ 13.3.2p2): A candidate function having fewer than m
6507 // parameters is viable only if it has an ellipsis in its parameter
6508 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006509 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006510 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006511 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006512 return;
6513 }
6514
6515 // Function types don't have any default arguments, so just check if
6516 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006517 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006518 // Not enough arguments.
6519 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006520 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006521 return;
6522 }
6523
6524 // Determine the implicit conversion sequences for each of the
6525 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006526 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006527 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006528 // (C++ 13.3.2p3): for F to be a viable function, there shall
6529 // exist for each argument an implicit conversion sequence
6530 // (13.3.3.1) that converts that argument to the corresponding
6531 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006532 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006533 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006534 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006535 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006536 /*InOverloadResolution=*/false,
6537 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006538 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006539 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006540 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006541 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006542 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006543 }
6544 } else {
6545 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6546 // argument for which there is no corresponding parameter is
6547 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006548 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006549 }
6550 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006551
Craig Topper5fc8fc22014-08-27 06:28:36 +00006552 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006553 Candidate.Viable = false;
6554 Candidate.FailureKind = ovl_fail_enable_if;
6555 Candidate.DeductionFailure.Data = FailedAttr;
6556 return;
6557 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006558}
6559
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006560/// \brief Add overload candidates for overloaded operators that are
6561/// member functions.
6562///
6563/// Add the overloaded operator candidates that are member functions
6564/// for the operator Op that was used in an operator expression such
6565/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6566/// CandidateSet will store the added overload candidates. (C++
6567/// [over.match.oper]).
6568void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6569 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006570 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006571 OverloadCandidateSet& CandidateSet,
6572 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006573 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6574
6575 // C++ [over.match.oper]p3:
6576 // For a unary operator @ with an operand of a type whose
6577 // cv-unqualified version is T1, and for a binary operator @ with
6578 // a left operand of a type whose cv-unqualified version is T1 and
6579 // a right operand of a type whose cv-unqualified version is T2,
6580 // three sets of candidate functions, designated member
6581 // candidates, non-member candidates and built-in candidates, are
6582 // constructed as follows:
6583 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006584
Richard Smith0feaf0c2013-04-20 12:41:22 +00006585 // -- If T1 is a complete class type or a class currently being
6586 // defined, the set of member candidates is the result of the
6587 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6588 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006589 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006590 // Complete the type if it can be completed.
6591 RequireCompleteType(OpLoc, T1, 0);
6592 // If the type is neither complete nor being defined, bail out now.
6593 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006594 return;
Mike Stump11289f42009-09-09 15:08:12 +00006595
John McCall27b18f82009-11-17 02:14:36 +00006596 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6597 LookupQualifiedName(Operators, T1Rec->getDecl());
6598 Operators.suppressDiagnostics();
6599
Mike Stump11289f42009-09-09 15:08:12 +00006600 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006601 OperEnd = Operators.end();
6602 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006603 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006604 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006605 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006606 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006607 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006608 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006609 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006610}
6611
Douglas Gregora11693b2008-11-12 17:17:38 +00006612/// AddBuiltinCandidate - Add a candidate for a built-in
6613/// operator. ResultTy and ParamTys are the result and parameter types
6614/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006615/// arguments being passed to the candidate. IsAssignmentOperator
6616/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006617/// operator. NumContextualBoolArguments is the number of arguments
6618/// (at the beginning of the argument list) that will be contextually
6619/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006620void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006621 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006622 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006623 bool IsAssignmentOperator,
6624 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006625 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006626 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006627
Douglas Gregora11693b2008-11-12 17:17:38 +00006628 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006629 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006630 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6631 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006632 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006633 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006634 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006635 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006636 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6637
6638 // Determine the implicit conversion sequences for each of the
6639 // arguments.
6640 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006641 Candidate.ExplicitCallArguments = Args.size();
6642 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006643 // C++ [over.match.oper]p4:
6644 // For the built-in assignment operators, conversions of the
6645 // left operand are restricted as follows:
6646 // -- no temporaries are introduced to hold the left operand, and
6647 // -- no user-defined conversions are applied to the left
6648 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006649 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006650 //
6651 // We block these conversions by turning off user-defined
6652 // conversions, since that is the only way that initialization of
6653 // a reference to a non-class type can occur from something that
6654 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006655 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006656 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006657 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006658 Candidate.Conversions[ArgIdx]
6659 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006660 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006661 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006662 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006663 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006664 /*InOverloadResolution=*/false,
6665 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006666 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006667 }
John McCall0d1da222010-01-12 00:44:57 +00006668 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006669 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006670 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006671 break;
6672 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006673 }
6674}
6675
Craig Toppercd7b0332013-07-01 06:29:40 +00006676namespace {
6677
Douglas Gregora11693b2008-11-12 17:17:38 +00006678/// BuiltinCandidateTypeSet - A set of types that will be used for the
6679/// candidate operator functions for built-in operators (C++
6680/// [over.built]). The types are separated into pointer types and
6681/// enumeration types.
6682class BuiltinCandidateTypeSet {
6683 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006684 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006685
6686 /// PointerTypes - The set of pointer types that will be used in the
6687 /// built-in candidates.
6688 TypeSet PointerTypes;
6689
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006690 /// MemberPointerTypes - The set of member pointer types that will be
6691 /// used in the built-in candidates.
6692 TypeSet MemberPointerTypes;
6693
Douglas Gregora11693b2008-11-12 17:17:38 +00006694 /// EnumerationTypes - The set of enumeration types that will be
6695 /// used in the built-in candidates.
6696 TypeSet EnumerationTypes;
6697
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006698 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006699 /// candidates.
6700 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006701
6702 /// \brief A flag indicating non-record types are viable candidates
6703 bool HasNonRecordTypes;
6704
6705 /// \brief A flag indicating whether either arithmetic or enumeration types
6706 /// were present in the candidate set.
6707 bool HasArithmeticOrEnumeralTypes;
6708
Douglas Gregor80af3132011-05-21 23:15:46 +00006709 /// \brief A flag indicating whether the nullptr type was present in the
6710 /// candidate set.
6711 bool HasNullPtrType;
6712
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006713 /// Sema - The semantic analysis instance where we are building the
6714 /// candidate type set.
6715 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006716
Douglas Gregora11693b2008-11-12 17:17:38 +00006717 /// Context - The AST context in which we will build the type sets.
6718 ASTContext &Context;
6719
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006720 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6721 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006722 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006723
6724public:
6725 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006726 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006727
Mike Stump11289f42009-09-09 15:08:12 +00006728 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006729 : HasNonRecordTypes(false),
6730 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006731 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006732 SemaRef(SemaRef),
6733 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006734
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006735 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006736 SourceLocation Loc,
6737 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006738 bool AllowExplicitConversions,
6739 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006740
6741 /// pointer_begin - First pointer type found;
6742 iterator pointer_begin() { return PointerTypes.begin(); }
6743
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006744 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006745 iterator pointer_end() { return PointerTypes.end(); }
6746
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006747 /// member_pointer_begin - First member pointer type found;
6748 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6749
6750 /// member_pointer_end - Past the last member pointer type found;
6751 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6752
Douglas Gregora11693b2008-11-12 17:17:38 +00006753 /// enumeration_begin - First enumeration type found;
6754 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6755
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006756 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006757 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006758
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006759 iterator vector_begin() { return VectorTypes.begin(); }
6760 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006761
6762 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6763 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006764 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006765};
6766
Craig Toppercd7b0332013-07-01 06:29:40 +00006767} // end anonymous namespace
6768
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006769/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006770/// the set of pointer types along with any more-qualified variants of
6771/// that type. For example, if @p Ty is "int const *", this routine
6772/// will add "int const *", "int const volatile *", "int const
6773/// restrict *", and "int const volatile restrict *" to the set of
6774/// pointer types. Returns true if the add of @p Ty itself succeeded,
6775/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006776///
6777/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006778bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006779BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6780 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006781
Douglas Gregora11693b2008-11-12 17:17:38 +00006782 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006783 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006784 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006785
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006786 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006787 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006788 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006789 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006790 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6791 PointeeTy = PTy->getPointeeType();
6792 buildObjCPtr = true;
6793 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006794 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006795 }
6796
Sebastian Redl4990a632009-11-18 20:39:26 +00006797 // Don't add qualified variants of arrays. For one, they're not allowed
6798 // (the qualifier would sink to the element type), and for another, the
6799 // only overload situation where it matters is subscript or pointer +- int,
6800 // and those shouldn't have qualifier variants anyway.
6801 if (PointeeTy->isArrayType())
6802 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006803
John McCall8ccfcb52009-09-24 19:53:00 +00006804 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006805 bool hasVolatile = VisibleQuals.hasVolatile();
6806 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006807
John McCall8ccfcb52009-09-24 19:53:00 +00006808 // Iterate through all strict supersets of BaseCVR.
6809 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6810 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006811 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006812 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006813
6814 // Skip over restrict if no restrict found anywhere in the types, or if
6815 // the type cannot be restrict-qualified.
6816 if ((CVR & Qualifiers::Restrict) &&
6817 (!hasRestrict ||
6818 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6819 continue;
6820
6821 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006822 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006823
6824 // Build qualified pointer type.
6825 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006826 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006827 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006828 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006829 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6830
6831 // Insert qualified pointer type.
6832 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006833 }
6834
6835 return true;
6836}
6837
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006838/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6839/// to the set of pointer types along with any more-qualified variants of
6840/// that type. For example, if @p Ty is "int const *", this routine
6841/// will add "int const *", "int const volatile *", "int const
6842/// restrict *", and "int const volatile restrict *" to the set of
6843/// pointer types. Returns true if the add of @p Ty itself succeeded,
6844/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006845///
6846/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006847bool
6848BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6849 QualType Ty) {
6850 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006851 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006852 return false;
6853
John McCall8ccfcb52009-09-24 19:53:00 +00006854 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6855 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006856
John McCall8ccfcb52009-09-24 19:53:00 +00006857 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006858 // Don't add qualified variants of arrays. For one, they're not allowed
6859 // (the qualifier would sink to the element type), and for another, the
6860 // only overload situation where it matters is subscript or pointer +- int,
6861 // and those shouldn't have qualifier variants anyway.
6862 if (PointeeTy->isArrayType())
6863 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006864 const Type *ClassTy = PointerTy->getClass();
6865
6866 // Iterate through all strict supersets of the pointee type's CVR
6867 // qualifiers.
6868 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6869 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6870 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006871
John McCall8ccfcb52009-09-24 19:53:00 +00006872 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006873 MemberPointerTypes.insert(
6874 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006875 }
6876
6877 return true;
6878}
6879
Douglas Gregora11693b2008-11-12 17:17:38 +00006880/// AddTypesConvertedFrom - Add each of the types to which the type @p
6881/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006882/// primarily interested in pointer types and enumeration types. We also
6883/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006884/// AllowUserConversions is true if we should look at the conversion
6885/// functions of a class type, and AllowExplicitConversions if we
6886/// should also include the explicit conversion functions of a class
6887/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006888void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006889BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006890 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006891 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006892 bool AllowExplicitConversions,
6893 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006894 // Only deal with canonical types.
6895 Ty = Context.getCanonicalType(Ty);
6896
6897 // Look through reference types; they aren't part of the type of an
6898 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006899 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006900 Ty = RefTy->getPointeeType();
6901
John McCall33ddac02011-01-19 10:06:00 +00006902 // If we're dealing with an array type, decay to the pointer.
6903 if (Ty->isArrayType())
6904 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6905
6906 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006907 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006908
Chandler Carruth00a38332010-12-13 01:44:01 +00006909 // Flag if we ever add a non-record type.
6910 const RecordType *TyRec = Ty->getAs<RecordType>();
6911 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6912
Chandler Carruth00a38332010-12-13 01:44:01 +00006913 // Flag if we encounter an arithmetic type.
6914 HasArithmeticOrEnumeralTypes =
6915 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6916
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006917 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6918 PointerTypes.insert(Ty);
6919 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006920 // Insert our type, and its more-qualified variants, into the set
6921 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006922 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006923 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006924 } else if (Ty->isMemberPointerType()) {
6925 // Member pointers are far easier, since the pointee can't be converted.
6926 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6927 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006928 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006929 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006930 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006931 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006932 // We treat vector types as arithmetic types in many contexts as an
6933 // extension.
6934 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006935 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006936 } else if (Ty->isNullPtrType()) {
6937 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006938 } else if (AllowUserConversions && TyRec) {
6939 // No conversion functions in incomplete types.
6940 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6941 return;
Mike Stump11289f42009-09-09 15:08:12 +00006942
Chandler Carruth00a38332010-12-13 01:44:01 +00006943 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00006944 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006945 if (isa<UsingShadowDecl>(D))
6946 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006947
Chandler Carruth00a38332010-12-13 01:44:01 +00006948 // Skip conversion function templates; they don't tell us anything
6949 // about which builtin types we can convert to.
6950 if (isa<FunctionTemplateDecl>(D))
6951 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006952
Chandler Carruth00a38332010-12-13 01:44:01 +00006953 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6954 if (AllowExplicitConversions || !Conv->isExplicit()) {
6955 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6956 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006957 }
6958 }
6959 }
6960}
6961
Douglas Gregor84605ae2009-08-24 13:43:27 +00006962/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6963/// the volatile- and non-volatile-qualified assignment operators for the
6964/// given type to the candidate set.
6965static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6966 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006967 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006968 OverloadCandidateSet &CandidateSet) {
6969 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006970
Douglas Gregor84605ae2009-08-24 13:43:27 +00006971 // T& operator=(T&, T)
6972 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6973 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006974 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006975 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006976
Douglas Gregor84605ae2009-08-24 13:43:27 +00006977 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6978 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006979 ParamTypes[0]
6980 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006981 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006982 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006983 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006984 }
6985}
Mike Stump11289f42009-09-09 15:08:12 +00006986
Sebastian Redl1054fae2009-10-25 17:03:50 +00006987/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6988/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006989static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6990 Qualifiers VRQuals;
6991 const RecordType *TyRec;
6992 if (const MemberPointerType *RHSMPType =
6993 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006994 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006995 else
6996 TyRec = ArgExpr->getType()->getAs<RecordType>();
6997 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006998 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006999 VRQuals.addVolatile();
7000 VRQuals.addRestrict();
7001 return VRQuals;
7002 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007003
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007004 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007005 if (!ClassDecl->hasDefinition())
7006 return VRQuals;
7007
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007008 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007009 if (isa<UsingShadowDecl>(D))
7010 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7011 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007012 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7013 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7014 CanTy = ResTypeRef->getPointeeType();
7015 // Need to go down the pointer/mempointer chain and add qualifiers
7016 // as see them.
7017 bool done = false;
7018 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007019 if (CanTy.isRestrictQualified())
7020 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007021 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7022 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007023 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007024 CanTy->getAs<MemberPointerType>())
7025 CanTy = ResTypeMPtr->getPointeeType();
7026 else
7027 done = true;
7028 if (CanTy.isVolatileQualified())
7029 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007030 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7031 return VRQuals;
7032 }
7033 }
7034 }
7035 return VRQuals;
7036}
John McCall52872982010-11-13 05:51:15 +00007037
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007038namespace {
John McCall52872982010-11-13 05:51:15 +00007039
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007040/// \brief Helper class to manage the addition of builtin operator overload
7041/// candidates. It provides shared state and utility methods used throughout
7042/// the process, as well as a helper method to add each group of builtin
7043/// operator overloads from the standard to a candidate set.
7044class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007045 // Common instance state available to all overload candidate addition methods.
7046 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007047 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007048 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007049 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007050 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007051 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007052
Chandler Carruthc6586e52010-12-12 10:35:00 +00007053 // Define some constants used to index and iterate over the arithemetic types
7054 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007055 // The "promoted arithmetic types" are the arithmetic
7056 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007057 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007058 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007059 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007060 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007061 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007062 LastPromotedArithmeticType = 11;
7063 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007064
Chandler Carruthc6586e52010-12-12 10:35:00 +00007065 /// \brief Get the canonical type for a given arithmetic type index.
7066 CanQualType getArithmeticType(unsigned index) {
7067 assert(index < NumArithmeticTypes);
7068 static CanQualType ASTContext::* const
7069 ArithmeticTypes[NumArithmeticTypes] = {
7070 // Start of promoted types.
7071 &ASTContext::FloatTy,
7072 &ASTContext::DoubleTy,
7073 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007074
Chandler Carruthc6586e52010-12-12 10:35:00 +00007075 // Start of integral types.
7076 &ASTContext::IntTy,
7077 &ASTContext::LongTy,
7078 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007079 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007080 &ASTContext::UnsignedIntTy,
7081 &ASTContext::UnsignedLongTy,
7082 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007083 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007084 // End of promoted types.
7085
7086 &ASTContext::BoolTy,
7087 &ASTContext::CharTy,
7088 &ASTContext::WCharTy,
7089 &ASTContext::Char16Ty,
7090 &ASTContext::Char32Ty,
7091 &ASTContext::SignedCharTy,
7092 &ASTContext::ShortTy,
7093 &ASTContext::UnsignedCharTy,
7094 &ASTContext::UnsignedShortTy,
7095 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007096 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007097 };
7098 return S.Context.*ArithmeticTypes[index];
7099 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007100
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007101 /// \brief Gets the canonical type resulting from the usual arithemetic
7102 /// converions for the given arithmetic types.
7103 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7104 // Accelerator table for performing the usual arithmetic conversions.
7105 // The rules are basically:
7106 // - if either is floating-point, use the wider floating-point
7107 // - if same signedness, use the higher rank
7108 // - if same size, use unsigned of the higher rank
7109 // - use the larger type
7110 // These rules, together with the axiom that higher ranks are
7111 // never smaller, are sufficient to precompute all of these results
7112 // *except* when dealing with signed types of higher rank.
7113 // (we could precompute SLL x UI for all known platforms, but it's
7114 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007115 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007116 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007117 Dep=-1,
7118 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007119 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007120 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007121 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007122/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7123/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7124/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7125/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7126/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7127/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7128/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7129/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7130/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7131/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7132/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007133 };
7134
7135 assert(L < LastPromotedArithmeticType);
7136 assert(R < LastPromotedArithmeticType);
7137 int Idx = ConversionsTable[L][R];
7138
7139 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007140 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007141
7142 // Slow path: we need to compare widths.
7143 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007144 CanQualType LT = getArithmeticType(L),
7145 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007146 unsigned LW = S.Context.getIntWidth(LT),
7147 RW = S.Context.getIntWidth(RT);
7148
7149 // If they're different widths, use the signed type.
7150 if (LW > RW) return LT;
7151 else if (LW < RW) return RT;
7152
7153 // Otherwise, use the unsigned type of the signed type's rank.
7154 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7155 assert(L == SLL || R == SLL);
7156 return S.Context.UnsignedLongLongTy;
7157 }
7158
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007159 /// \brief Helper method to factor out the common pattern of adding overloads
7160 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007161 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007162 bool HasVolatile,
7163 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007164 QualType ParamTypes[2] = {
7165 S.Context.getLValueReferenceType(CandidateTy),
7166 S.Context.IntTy
7167 };
7168
7169 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007170 if (Args.size() == 1)
7171 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007172 else
Richard Smithe54c3072013-05-05 15:51:06 +00007173 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007174
7175 // Use a heuristic to reduce number of builtin candidates in the set:
7176 // add volatile version only if there are conversions to a volatile type.
7177 if (HasVolatile) {
7178 ParamTypes[0] =
7179 S.Context.getLValueReferenceType(
7180 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007181 if (Args.size() == 1)
7182 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007183 else
Richard Smithe54c3072013-05-05 15:51:06 +00007184 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007185 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007186
7187 // Add restrict version only if there are conversions to a restrict type
7188 // and our candidate type is a non-restrict-qualified pointer.
7189 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7190 !CandidateTy.isRestrictQualified()) {
7191 ParamTypes[0]
7192 = S.Context.getLValueReferenceType(
7193 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007194 if (Args.size() == 1)
7195 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007196 else
Richard Smithe54c3072013-05-05 15:51:06 +00007197 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007198
7199 if (HasVolatile) {
7200 ParamTypes[0]
7201 = S.Context.getLValueReferenceType(
7202 S.Context.getCVRQualifiedType(CandidateTy,
7203 (Qualifiers::Volatile |
7204 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007205 if (Args.size() == 1)
7206 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007207 else
Richard Smithe54c3072013-05-05 15:51:06 +00007208 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007209 }
7210 }
7211
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007212 }
7213
7214public:
7215 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007216 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007217 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007218 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007219 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007220 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007221 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007222 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007223 HasArithmeticOrEnumeralCandidateType(
7224 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007225 CandidateTypes(CandidateTypes),
7226 CandidateSet(CandidateSet) {
7227 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007228 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007229 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007230 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007231 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007232 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007233 assert(getArithmeticType(FirstPromotedArithmeticType)
7234 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007235 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007236 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007237 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007238 "Invalid last promoted arithmetic type");
7239 }
7240
7241 // C++ [over.built]p3:
7242 //
7243 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7244 // is either volatile or empty, there exist candidate operator
7245 // functions of the form
7246 //
7247 // VQ T& operator++(VQ T&);
7248 // T operator++(VQ T&, int);
7249 //
7250 // C++ [over.built]p4:
7251 //
7252 // For every pair (T, VQ), where T is an arithmetic type other
7253 // than bool, and VQ is either volatile or empty, there exist
7254 // candidate operator functions of the form
7255 //
7256 // VQ T& operator--(VQ T&);
7257 // T operator--(VQ T&, int);
7258 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007259 if (!HasArithmeticOrEnumeralCandidateType)
7260 return;
7261
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007262 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7263 Arith < NumArithmeticTypes; ++Arith) {
7264 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007265 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007266 VisibleTypeConversionsQuals.hasVolatile(),
7267 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007268 }
7269 }
7270
7271 // C++ [over.built]p5:
7272 //
7273 // For every pair (T, VQ), where T is a cv-qualified or
7274 // cv-unqualified object type, and VQ is either volatile or
7275 // empty, there exist candidate operator functions of the form
7276 //
7277 // T*VQ& operator++(T*VQ&);
7278 // T*VQ& operator--(T*VQ&);
7279 // T* operator++(T*VQ&, int);
7280 // T* operator--(T*VQ&, int);
7281 void addPlusPlusMinusMinusPointerOverloads() {
7282 for (BuiltinCandidateTypeSet::iterator
7283 Ptr = CandidateTypes[0].pointer_begin(),
7284 PtrEnd = CandidateTypes[0].pointer_end();
7285 Ptr != PtrEnd; ++Ptr) {
7286 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007287 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007288 continue;
7289
7290 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007291 (!(*Ptr).isVolatileQualified() &&
7292 VisibleTypeConversionsQuals.hasVolatile()),
7293 (!(*Ptr).isRestrictQualified() &&
7294 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007295 }
7296 }
7297
7298 // C++ [over.built]p6:
7299 // For every cv-qualified or cv-unqualified object type T, there
7300 // exist candidate operator functions of the form
7301 //
7302 // T& operator*(T*);
7303 //
7304 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007305 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007306 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007307 // T& operator*(T*);
7308 void addUnaryStarPointerOverloads() {
7309 for (BuiltinCandidateTypeSet::iterator
7310 Ptr = CandidateTypes[0].pointer_begin(),
7311 PtrEnd = CandidateTypes[0].pointer_end();
7312 Ptr != PtrEnd; ++Ptr) {
7313 QualType ParamTy = *Ptr;
7314 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007315 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7316 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007317
Douglas Gregor02824322011-01-26 19:30:28 +00007318 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7319 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7320 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007321
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007322 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007323 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007324 }
7325 }
7326
7327 // C++ [over.built]p9:
7328 // For every promoted arithmetic type T, there exist candidate
7329 // operator functions of the form
7330 //
7331 // T operator+(T);
7332 // T operator-(T);
7333 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007334 if (!HasArithmeticOrEnumeralCandidateType)
7335 return;
7336
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007337 for (unsigned Arith = FirstPromotedArithmeticType;
7338 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007339 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007340 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007341 }
7342
7343 // Extension: We also add these operators for vector types.
7344 for (BuiltinCandidateTypeSet::iterator
7345 Vec = CandidateTypes[0].vector_begin(),
7346 VecEnd = CandidateTypes[0].vector_end();
7347 Vec != VecEnd; ++Vec) {
7348 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007349 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007350 }
7351 }
7352
7353 // C++ [over.built]p8:
7354 // For every type T, there exist candidate operator functions of
7355 // the form
7356 //
7357 // T* operator+(T*);
7358 void addUnaryPlusPointerOverloads() {
7359 for (BuiltinCandidateTypeSet::iterator
7360 Ptr = CandidateTypes[0].pointer_begin(),
7361 PtrEnd = CandidateTypes[0].pointer_end();
7362 Ptr != PtrEnd; ++Ptr) {
7363 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007364 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007365 }
7366 }
7367
7368 // C++ [over.built]p10:
7369 // For every promoted integral type T, there exist candidate
7370 // operator functions of the form
7371 //
7372 // T operator~(T);
7373 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007374 if (!HasArithmeticOrEnumeralCandidateType)
7375 return;
7376
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007377 for (unsigned Int = FirstPromotedIntegralType;
7378 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007379 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007380 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007381 }
7382
7383 // Extension: We also add this operator for vector types.
7384 for (BuiltinCandidateTypeSet::iterator
7385 Vec = CandidateTypes[0].vector_begin(),
7386 VecEnd = CandidateTypes[0].vector_end();
7387 Vec != VecEnd; ++Vec) {
7388 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007389 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007390 }
7391 }
7392
7393 // C++ [over.match.oper]p16:
7394 // For every pointer to member type T, there exist candidate operator
7395 // functions of the form
7396 //
7397 // bool operator==(T,T);
7398 // bool operator!=(T,T);
7399 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7400 /// Set of (canonical) types that we've already handled.
7401 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7402
Richard Smithe54c3072013-05-05 15:51:06 +00007403 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007404 for (BuiltinCandidateTypeSet::iterator
7405 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7406 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7407 MemPtr != MemPtrEnd;
7408 ++MemPtr) {
7409 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007410 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007411 continue;
7412
7413 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007414 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007415 }
7416 }
7417 }
7418
7419 // C++ [over.built]p15:
7420 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007421 // For every T, where T is an enumeration type, a pointer type, or
7422 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007423 //
7424 // bool operator<(T, T);
7425 // bool operator>(T, T);
7426 // bool operator<=(T, T);
7427 // bool operator>=(T, T);
7428 // bool operator==(T, T);
7429 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007430 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007431 // C++ [over.match.oper]p3:
7432 // [...]the built-in candidates include all of the candidate operator
7433 // functions defined in 13.6 that, compared to the given operator, [...]
7434 // do not have the same parameter-type-list as any non-template non-member
7435 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007436 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007437 // Note that in practice, this only affects enumeration types because there
7438 // aren't any built-in candidates of record type, and a user-defined operator
7439 // must have an operand of record or enumeration type. Also, the only other
7440 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007441 // cannot be overloaded for enumeration types, so this is the only place
7442 // where we must suppress candidates like this.
7443 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7444 UserDefinedBinaryOperators;
7445
Richard Smithe54c3072013-05-05 15:51:06 +00007446 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007447 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7448 CandidateTypes[ArgIdx].enumeration_end()) {
7449 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7450 CEnd = CandidateSet.end();
7451 C != CEnd; ++C) {
7452 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7453 continue;
7454
Eli Friedman14f082b2012-09-18 21:52:24 +00007455 if (C->Function->isFunctionTemplateSpecialization())
7456 continue;
7457
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007458 QualType FirstParamType =
7459 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7460 QualType SecondParamType =
7461 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7462
7463 // Skip if either parameter isn't of enumeral type.
7464 if (!FirstParamType->isEnumeralType() ||
7465 !SecondParamType->isEnumeralType())
7466 continue;
7467
7468 // Add this operator to the set of known user-defined operators.
7469 UserDefinedBinaryOperators.insert(
7470 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7471 S.Context.getCanonicalType(SecondParamType)));
7472 }
7473 }
7474 }
7475
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007476 /// Set of (canonical) types that we've already handled.
7477 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7478
Richard Smithe54c3072013-05-05 15:51:06 +00007479 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007480 for (BuiltinCandidateTypeSet::iterator
7481 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7482 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7483 Ptr != PtrEnd; ++Ptr) {
7484 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007485 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007486 continue;
7487
7488 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007489 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007490 }
7491 for (BuiltinCandidateTypeSet::iterator
7492 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7493 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7494 Enum != EnumEnd; ++Enum) {
7495 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7496
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007497 // Don't add the same builtin candidate twice, or if a user defined
7498 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007499 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007500 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7501 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007502 continue;
7503
7504 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007505 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007506 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007507
7508 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7509 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007510 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007511 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007512 NullPtrTy))) {
7513 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007514 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007515 CandidateSet);
7516 }
7517 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007518 }
7519 }
7520
7521 // C++ [over.built]p13:
7522 //
7523 // For every cv-qualified or cv-unqualified object type T
7524 // there exist candidate operator functions of the form
7525 //
7526 // T* operator+(T*, ptrdiff_t);
7527 // T& operator[](T*, ptrdiff_t); [BELOW]
7528 // T* operator-(T*, ptrdiff_t);
7529 // T* operator+(ptrdiff_t, T*);
7530 // T& operator[](ptrdiff_t, T*); [BELOW]
7531 //
7532 // C++ [over.built]p14:
7533 //
7534 // For every T, where T is a pointer to object type, there
7535 // exist candidate operator functions of the form
7536 //
7537 // ptrdiff_t operator-(T, T);
7538 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7539 /// Set of (canonical) types that we've already handled.
7540 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7541
7542 for (int Arg = 0; Arg < 2; ++Arg) {
7543 QualType AsymetricParamTypes[2] = {
7544 S.Context.getPointerDiffType(),
7545 S.Context.getPointerDiffType(),
7546 };
7547 for (BuiltinCandidateTypeSet::iterator
7548 Ptr = CandidateTypes[Arg].pointer_begin(),
7549 PtrEnd = CandidateTypes[Arg].pointer_end();
7550 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007551 QualType PointeeTy = (*Ptr)->getPointeeType();
7552 if (!PointeeTy->isObjectType())
7553 continue;
7554
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007555 AsymetricParamTypes[Arg] = *Ptr;
7556 if (Arg == 0 || Op == OO_Plus) {
7557 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7558 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007559 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007560 }
7561 if (Op == OO_Minus) {
7562 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007563 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007564 continue;
7565
7566 QualType ParamTypes[2] = { *Ptr, *Ptr };
7567 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007568 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007569 }
7570 }
7571 }
7572 }
7573
7574 // C++ [over.built]p12:
7575 //
7576 // For every pair of promoted arithmetic types L and R, there
7577 // exist candidate operator functions of the form
7578 //
7579 // LR operator*(L, R);
7580 // LR operator/(L, R);
7581 // LR operator+(L, R);
7582 // LR operator-(L, R);
7583 // bool operator<(L, R);
7584 // bool operator>(L, R);
7585 // bool operator<=(L, R);
7586 // bool operator>=(L, R);
7587 // bool operator==(L, R);
7588 // bool operator!=(L, R);
7589 //
7590 // where LR is the result of the usual arithmetic conversions
7591 // between types L and R.
7592 //
7593 // C++ [over.built]p24:
7594 //
7595 // For every pair of promoted arithmetic types L and R, there exist
7596 // candidate operator functions of the form
7597 //
7598 // LR operator?(bool, L, R);
7599 //
7600 // where LR is the result of the usual arithmetic conversions
7601 // between types L and R.
7602 // Our candidates ignore the first parameter.
7603 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007604 if (!HasArithmeticOrEnumeralCandidateType)
7605 return;
7606
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007607 for (unsigned Left = FirstPromotedArithmeticType;
7608 Left < LastPromotedArithmeticType; ++Left) {
7609 for (unsigned Right = FirstPromotedArithmeticType;
7610 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007611 QualType LandR[2] = { getArithmeticType(Left),
7612 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007613 QualType Result =
7614 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007615 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007616 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007617 }
7618 }
7619
7620 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7621 // conditional operator for vector types.
7622 for (BuiltinCandidateTypeSet::iterator
7623 Vec1 = CandidateTypes[0].vector_begin(),
7624 Vec1End = CandidateTypes[0].vector_end();
7625 Vec1 != Vec1End; ++Vec1) {
7626 for (BuiltinCandidateTypeSet::iterator
7627 Vec2 = CandidateTypes[1].vector_begin(),
7628 Vec2End = CandidateTypes[1].vector_end();
7629 Vec2 != Vec2End; ++Vec2) {
7630 QualType LandR[2] = { *Vec1, *Vec2 };
7631 QualType Result = S.Context.BoolTy;
7632 if (!isComparison) {
7633 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7634 Result = *Vec1;
7635 else
7636 Result = *Vec2;
7637 }
7638
Richard Smithe54c3072013-05-05 15:51:06 +00007639 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007640 }
7641 }
7642 }
7643
7644 // C++ [over.built]p17:
7645 //
7646 // For every pair of promoted integral types L and R, there
7647 // exist candidate operator functions of the form
7648 //
7649 // LR operator%(L, R);
7650 // LR operator&(L, R);
7651 // LR operator^(L, R);
7652 // LR operator|(L, R);
7653 // L operator<<(L, R);
7654 // L operator>>(L, R);
7655 //
7656 // where LR is the result of the usual arithmetic conversions
7657 // between types L and R.
7658 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007659 if (!HasArithmeticOrEnumeralCandidateType)
7660 return;
7661
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007662 for (unsigned Left = FirstPromotedIntegralType;
7663 Left < LastPromotedIntegralType; ++Left) {
7664 for (unsigned Right = FirstPromotedIntegralType;
7665 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007666 QualType LandR[2] = { getArithmeticType(Left),
7667 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007668 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7669 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007670 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007671 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007672 }
7673 }
7674 }
7675
7676 // C++ [over.built]p20:
7677 //
7678 // For every pair (T, VQ), where T is an enumeration or
7679 // pointer to member type and VQ is either volatile or
7680 // empty, there exist candidate operator functions of the form
7681 //
7682 // VQ T& operator=(VQ T&, T);
7683 void addAssignmentMemberPointerOrEnumeralOverloads() {
7684 /// Set of (canonical) types that we've already handled.
7685 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7686
7687 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7688 for (BuiltinCandidateTypeSet::iterator
7689 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7690 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7691 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007692 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007693 continue;
7694
Richard Smithe54c3072013-05-05 15:51:06 +00007695 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007696 }
7697
7698 for (BuiltinCandidateTypeSet::iterator
7699 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7700 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7701 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007702 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007703 continue;
7704
Richard Smithe54c3072013-05-05 15:51:06 +00007705 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007706 }
7707 }
7708 }
7709
7710 // C++ [over.built]p19:
7711 //
7712 // For every pair (T, VQ), where T is any type and VQ is either
7713 // volatile or empty, there exist candidate operator functions
7714 // of the form
7715 //
7716 // T*VQ& operator=(T*VQ&, T*);
7717 //
7718 // C++ [over.built]p21:
7719 //
7720 // For every pair (T, VQ), where T is a cv-qualified or
7721 // cv-unqualified object type and VQ is either volatile or
7722 // empty, there exist candidate operator functions of the form
7723 //
7724 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7725 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7726 void addAssignmentPointerOverloads(bool isEqualOp) {
7727 /// Set of (canonical) types that we've already handled.
7728 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7729
7730 for (BuiltinCandidateTypeSet::iterator
7731 Ptr = CandidateTypes[0].pointer_begin(),
7732 PtrEnd = CandidateTypes[0].pointer_end();
7733 Ptr != PtrEnd; ++Ptr) {
7734 // If this is operator=, keep track of the builtin candidates we added.
7735 if (isEqualOp)
7736 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007737 else if (!(*Ptr)->getPointeeType()->isObjectType())
7738 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007739
7740 // non-volatile version
7741 QualType ParamTypes[2] = {
7742 S.Context.getLValueReferenceType(*Ptr),
7743 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7744 };
Richard Smithe54c3072013-05-05 15:51:06 +00007745 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007746 /*IsAssigmentOperator=*/ isEqualOp);
7747
Douglas Gregor5bee2582012-06-04 00:15:09 +00007748 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7749 VisibleTypeConversionsQuals.hasVolatile();
7750 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007751 // volatile version
7752 ParamTypes[0] =
7753 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007754 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007755 /*IsAssigmentOperator=*/isEqualOp);
7756 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007757
7758 if (!(*Ptr).isRestrictQualified() &&
7759 VisibleTypeConversionsQuals.hasRestrict()) {
7760 // restrict version
7761 ParamTypes[0]
7762 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007763 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007764 /*IsAssigmentOperator=*/isEqualOp);
7765
7766 if (NeedVolatile) {
7767 // volatile restrict version
7768 ParamTypes[0]
7769 = S.Context.getLValueReferenceType(
7770 S.Context.getCVRQualifiedType(*Ptr,
7771 (Qualifiers::Volatile |
7772 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007773 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007774 /*IsAssigmentOperator=*/isEqualOp);
7775 }
7776 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007777 }
7778
7779 if (isEqualOp) {
7780 for (BuiltinCandidateTypeSet::iterator
7781 Ptr = CandidateTypes[1].pointer_begin(),
7782 PtrEnd = CandidateTypes[1].pointer_end();
7783 Ptr != PtrEnd; ++Ptr) {
7784 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007785 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007786 continue;
7787
Chandler Carruth8e543b32010-12-12 08:17:55 +00007788 QualType ParamTypes[2] = {
7789 S.Context.getLValueReferenceType(*Ptr),
7790 *Ptr,
7791 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007792
7793 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007794 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007795 /*IsAssigmentOperator=*/true);
7796
Douglas Gregor5bee2582012-06-04 00:15:09 +00007797 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7798 VisibleTypeConversionsQuals.hasVolatile();
7799 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007800 // volatile version
7801 ParamTypes[0] =
7802 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007803 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7804 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007805 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007806
7807 if (!(*Ptr).isRestrictQualified() &&
7808 VisibleTypeConversionsQuals.hasRestrict()) {
7809 // restrict version
7810 ParamTypes[0]
7811 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007812 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7813 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007814
7815 if (NeedVolatile) {
7816 // volatile restrict version
7817 ParamTypes[0]
7818 = S.Context.getLValueReferenceType(
7819 S.Context.getCVRQualifiedType(*Ptr,
7820 (Qualifiers::Volatile |
7821 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007822 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7823 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007824 }
7825 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007826 }
7827 }
7828 }
7829
7830 // C++ [over.built]p18:
7831 //
7832 // For every triple (L, VQ, R), where L is an arithmetic type,
7833 // VQ is either volatile or empty, and R is a promoted
7834 // arithmetic type, there exist candidate operator functions of
7835 // the form
7836 //
7837 // VQ L& operator=(VQ L&, R);
7838 // VQ L& operator*=(VQ L&, R);
7839 // VQ L& operator/=(VQ L&, R);
7840 // VQ L& operator+=(VQ L&, R);
7841 // VQ L& operator-=(VQ L&, R);
7842 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007843 if (!HasArithmeticOrEnumeralCandidateType)
7844 return;
7845
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007846 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7847 for (unsigned Right = FirstPromotedArithmeticType;
7848 Right < LastPromotedArithmeticType; ++Right) {
7849 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007850 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007851
7852 // Add this built-in operator as a candidate (VQ is empty).
7853 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007854 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007855 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007856 /*IsAssigmentOperator=*/isEqualOp);
7857
7858 // Add this built-in operator as a candidate (VQ is 'volatile').
7859 if (VisibleTypeConversionsQuals.hasVolatile()) {
7860 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007861 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007862 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007863 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007864 /*IsAssigmentOperator=*/isEqualOp);
7865 }
7866 }
7867 }
7868
7869 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7870 for (BuiltinCandidateTypeSet::iterator
7871 Vec1 = CandidateTypes[0].vector_begin(),
7872 Vec1End = CandidateTypes[0].vector_end();
7873 Vec1 != Vec1End; ++Vec1) {
7874 for (BuiltinCandidateTypeSet::iterator
7875 Vec2 = CandidateTypes[1].vector_begin(),
7876 Vec2End = CandidateTypes[1].vector_end();
7877 Vec2 != Vec2End; ++Vec2) {
7878 QualType ParamTypes[2];
7879 ParamTypes[1] = *Vec2;
7880 // Add this built-in operator as a candidate (VQ is empty).
7881 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007882 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007883 /*IsAssigmentOperator=*/isEqualOp);
7884
7885 // Add this built-in operator as a candidate (VQ is 'volatile').
7886 if (VisibleTypeConversionsQuals.hasVolatile()) {
7887 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7888 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007889 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007890 /*IsAssigmentOperator=*/isEqualOp);
7891 }
7892 }
7893 }
7894 }
7895
7896 // C++ [over.built]p22:
7897 //
7898 // For every triple (L, VQ, R), where L is an integral type, VQ
7899 // is either volatile or empty, and R is a promoted integral
7900 // type, there exist candidate operator functions of the form
7901 //
7902 // VQ L& operator%=(VQ L&, R);
7903 // VQ L& operator<<=(VQ L&, R);
7904 // VQ L& operator>>=(VQ L&, R);
7905 // VQ L& operator&=(VQ L&, R);
7906 // VQ L& operator^=(VQ L&, R);
7907 // VQ L& operator|=(VQ L&, R);
7908 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007909 if (!HasArithmeticOrEnumeralCandidateType)
7910 return;
7911
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007912 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7913 for (unsigned Right = FirstPromotedIntegralType;
7914 Right < LastPromotedIntegralType; ++Right) {
7915 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007916 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007917
7918 // Add this built-in operator as a candidate (VQ is empty).
7919 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007920 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007921 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007922 if (VisibleTypeConversionsQuals.hasVolatile()) {
7923 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007924 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007925 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7926 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007927 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007928 }
7929 }
7930 }
7931 }
7932
7933 // C++ [over.operator]p23:
7934 //
7935 // There also exist candidate operator functions of the form
7936 //
7937 // bool operator!(bool);
7938 // bool operator&&(bool, bool);
7939 // bool operator||(bool, bool);
7940 void addExclaimOverload() {
7941 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007942 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007943 /*IsAssignmentOperator=*/false,
7944 /*NumContextualBoolArguments=*/1);
7945 }
7946 void addAmpAmpOrPipePipeOverload() {
7947 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007948 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007949 /*IsAssignmentOperator=*/false,
7950 /*NumContextualBoolArguments=*/2);
7951 }
7952
7953 // C++ [over.built]p13:
7954 //
7955 // For every cv-qualified or cv-unqualified object type T there
7956 // exist candidate operator functions of the form
7957 //
7958 // T* operator+(T*, ptrdiff_t); [ABOVE]
7959 // T& operator[](T*, ptrdiff_t);
7960 // T* operator-(T*, ptrdiff_t); [ABOVE]
7961 // T* operator+(ptrdiff_t, T*); [ABOVE]
7962 // T& operator[](ptrdiff_t, T*);
7963 void addSubscriptOverloads() {
7964 for (BuiltinCandidateTypeSet::iterator
7965 Ptr = CandidateTypes[0].pointer_begin(),
7966 PtrEnd = CandidateTypes[0].pointer_end();
7967 Ptr != PtrEnd; ++Ptr) {
7968 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7969 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007970 if (!PointeeType->isObjectType())
7971 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007972
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007973 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7974
7975 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007976 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007977 }
7978
7979 for (BuiltinCandidateTypeSet::iterator
7980 Ptr = CandidateTypes[1].pointer_begin(),
7981 PtrEnd = CandidateTypes[1].pointer_end();
7982 Ptr != PtrEnd; ++Ptr) {
7983 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7984 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007985 if (!PointeeType->isObjectType())
7986 continue;
7987
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007988 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7989
7990 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00007991 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007992 }
7993 }
7994
7995 // C++ [over.built]p11:
7996 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7997 // C1 is the same type as C2 or is a derived class of C2, T is an object
7998 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7999 // there exist candidate operator functions of the form
8000 //
8001 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8002 //
8003 // where CV12 is the union of CV1 and CV2.
8004 void addArrowStarOverloads() {
8005 for (BuiltinCandidateTypeSet::iterator
8006 Ptr = CandidateTypes[0].pointer_begin(),
8007 PtrEnd = CandidateTypes[0].pointer_end();
8008 Ptr != PtrEnd; ++Ptr) {
8009 QualType C1Ty = (*Ptr);
8010 QualType C1;
8011 QualifierCollector Q1;
8012 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8013 if (!isa<RecordType>(C1))
8014 continue;
8015 // heuristic to reduce number of builtin candidates in the set.
8016 // Add volatile/restrict version only if there are conversions to a
8017 // volatile/restrict type.
8018 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8019 continue;
8020 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8021 continue;
8022 for (BuiltinCandidateTypeSet::iterator
8023 MemPtr = CandidateTypes[1].member_pointer_begin(),
8024 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8025 MemPtr != MemPtrEnd; ++MemPtr) {
8026 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8027 QualType C2 = QualType(mptr->getClass(), 0);
8028 C2 = C2.getUnqualifiedType();
8029 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8030 break;
8031 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8032 // build CV12 T&
8033 QualType T = mptr->getPointeeType();
8034 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8035 T.isVolatileQualified())
8036 continue;
8037 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8038 T.isRestrictQualified())
8039 continue;
8040 T = Q1.apply(S.Context, T);
8041 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008042 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008043 }
8044 }
8045 }
8046
8047 // Note that we don't consider the first argument, since it has been
8048 // contextually converted to bool long ago. The candidates below are
8049 // therefore added as binary.
8050 //
8051 // C++ [over.built]p25:
8052 // For every type T, where T is a pointer, pointer-to-member, or scoped
8053 // enumeration type, there exist candidate operator functions of the form
8054 //
8055 // T operator?(bool, T, T);
8056 //
8057 void addConditionalOperatorOverloads() {
8058 /// Set of (canonical) types that we've already handled.
8059 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8060
8061 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8062 for (BuiltinCandidateTypeSet::iterator
8063 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8064 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8065 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008066 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008067 continue;
8068
8069 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008070 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008071 }
8072
8073 for (BuiltinCandidateTypeSet::iterator
8074 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8075 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8076 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008077 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008078 continue;
8079
8080 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008081 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008082 }
8083
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008084 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008085 for (BuiltinCandidateTypeSet::iterator
8086 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8087 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8088 Enum != EnumEnd; ++Enum) {
8089 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8090 continue;
8091
David Blaikie82e95a32014-11-19 07:49:47 +00008092 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008093 continue;
8094
8095 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008096 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008097 }
8098 }
8099 }
8100 }
8101};
8102
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008103} // end anonymous namespace
8104
8105/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8106/// operator overloads to the candidate set (C++ [over.built]), based
8107/// on the operator @p Op and the arguments given. For example, if the
8108/// operator is a binary '+', this routine might add "int
8109/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008110void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8111 SourceLocation OpLoc,
8112 ArrayRef<Expr *> Args,
8113 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008114 // Find all of the types that the arguments can convert to, but only
8115 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008116 // that make use of these types. Also record whether we encounter non-record
8117 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008118 Qualifiers VisibleTypeConversionsQuals;
8119 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008120 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008121 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008122
8123 bool HasNonRecordCandidateType = false;
8124 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008125 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008126 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008127 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008128 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8129 OpLoc,
8130 true,
8131 (Op == OO_Exclaim ||
8132 Op == OO_AmpAmp ||
8133 Op == OO_PipePipe),
8134 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008135 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8136 CandidateTypes[ArgIdx].hasNonRecordTypes();
8137 HasArithmeticOrEnumeralCandidateType =
8138 HasArithmeticOrEnumeralCandidateType ||
8139 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008140 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008141
Chandler Carruth00a38332010-12-13 01:44:01 +00008142 // Exit early when no non-record types have been added to the candidate set
8143 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008144 //
8145 // We can't exit early for !, ||, or &&, since there we have always have
8146 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008147 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008148 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008149 return;
8150
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008151 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008152 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008153 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008154 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008155 CandidateTypes, CandidateSet);
8156
8157 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008158 switch (Op) {
8159 case OO_None:
8160 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008161 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008162
Chandler Carruth5184de02010-12-12 08:51:33 +00008163 case OO_New:
8164 case OO_Delete:
8165 case OO_Array_New:
8166 case OO_Array_Delete:
8167 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008168 llvm_unreachable(
8169 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008170
8171 case OO_Comma:
8172 case OO_Arrow:
8173 // C++ [over.match.oper]p3:
8174 // -- For the operator ',', the unary operator '&', or the
8175 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008176 break;
8177
8178 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008179 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008180 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008181 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008182
8183 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008184 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008185 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008186 } else {
8187 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8188 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8189 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008190 break;
8191
Chandler Carruth5184de02010-12-12 08:51:33 +00008192 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008193 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008194 OpBuilder.addUnaryStarPointerOverloads();
8195 else
8196 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8197 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008198
Chandler Carruth5184de02010-12-12 08:51:33 +00008199 case OO_Slash:
8200 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008201 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008202
8203 case OO_PlusPlus:
8204 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008205 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8206 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008207 break;
8208
Douglas Gregor84605ae2009-08-24 13:43:27 +00008209 case OO_EqualEqual:
8210 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008211 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008212 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008213
Douglas Gregora11693b2008-11-12 17:17:38 +00008214 case OO_Less:
8215 case OO_Greater:
8216 case OO_LessEqual:
8217 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008218 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008219 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8220 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008221
Douglas Gregora11693b2008-11-12 17:17:38 +00008222 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008223 case OO_Caret:
8224 case OO_Pipe:
8225 case OO_LessLess:
8226 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008227 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008228 break;
8229
Chandler Carruth5184de02010-12-12 08:51:33 +00008230 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008231 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008232 // C++ [over.match.oper]p3:
8233 // -- For the operator ',', the unary operator '&', or the
8234 // operator '->', the built-in candidates set is empty.
8235 break;
8236
8237 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8238 break;
8239
8240 case OO_Tilde:
8241 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8242 break;
8243
Douglas Gregora11693b2008-11-12 17:17:38 +00008244 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008245 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008246 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008247
8248 case OO_PlusEqual:
8249 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008250 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008251 // Fall through.
8252
8253 case OO_StarEqual:
8254 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008255 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008256 break;
8257
8258 case OO_PercentEqual:
8259 case OO_LessLessEqual:
8260 case OO_GreaterGreaterEqual:
8261 case OO_AmpEqual:
8262 case OO_CaretEqual:
8263 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008264 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008265 break;
8266
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008267 case OO_Exclaim:
8268 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008269 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008270
Douglas Gregora11693b2008-11-12 17:17:38 +00008271 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008272 case OO_PipePipe:
8273 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008274 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008275
8276 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008277 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008278 break;
8279
8280 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008281 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008282 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008283
8284 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008285 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008286 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8287 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008288 }
8289}
8290
Douglas Gregore254f902009-02-04 00:32:51 +00008291/// \brief Add function candidates found via argument-dependent lookup
8292/// to the set of overloading candidates.
8293///
8294/// This routine performs argument-dependent name lookup based on the
8295/// given function name (which may also be an operator name) and adds
8296/// all of the overload candidates found by ADL to the overload
8297/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008298void
Douglas Gregore254f902009-02-04 00:32:51 +00008299Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008300 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008301 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008302 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008303 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008304 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008305 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008306
John McCall91f61fc2010-01-26 06:04:06 +00008307 // FIXME: This approach for uniquing ADL results (and removing
8308 // redundant candidates from the set) relies on pointer-equality,
8309 // which means we need to key off the canonical decl. However,
8310 // always going back to the canonical decl might not get us the
8311 // right set of default arguments. What default arguments are
8312 // we supposed to consider on ADL candidates, anyway?
8313
Douglas Gregorcabea402009-09-22 15:41:20 +00008314 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008315 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008316
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008317 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008318 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8319 CandEnd = CandidateSet.end();
8320 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008321 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008322 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008323 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008324 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008325 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008326
8327 // For each of the ADL candidates we found, add it to the overload
8328 // set.
John McCall8fe68082010-01-26 07:16:45 +00008329 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008330 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008331 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008332 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008333 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008334
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008335 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8336 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008337 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008338 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008339 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008340 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008341 }
Douglas Gregore254f902009-02-04 00:32:51 +00008342}
8343
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008344/// isBetterOverloadCandidate - Determines whether the first overload
8345/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008346bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8347 const OverloadCandidate &Cand2,
8348 SourceLocation Loc,
8349 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008350 // Define viable functions to be better candidates than non-viable
8351 // functions.
8352 if (!Cand2.Viable)
8353 return Cand1.Viable;
8354 else if (!Cand1.Viable)
8355 return false;
8356
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008357 // C++ [over.match.best]p1:
8358 //
8359 // -- if F is a static member function, ICS1(F) is defined such
8360 // that ICS1(F) is neither better nor worse than ICS1(G) for
8361 // any function G, and, symmetrically, ICS1(G) is neither
8362 // better nor worse than ICS1(F).
8363 unsigned StartArg = 0;
8364 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8365 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008366
Douglas Gregord3cb3562009-07-07 23:38:56 +00008367 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008368 // A viable function F1 is defined to be a better function than another
8369 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008370 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008371 unsigned NumArgs = Cand1.NumConversions;
8372 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008373 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008374 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008375 switch (CompareImplicitConversionSequences(S,
8376 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008377 Cand2.Conversions[ArgIdx])) {
8378 case ImplicitConversionSequence::Better:
8379 // Cand1 has a better conversion sequence.
8380 HasBetterConversion = true;
8381 break;
8382
8383 case ImplicitConversionSequence::Worse:
8384 // Cand1 can't be better than Cand2.
8385 return false;
8386
8387 case ImplicitConversionSequence::Indistinguishable:
8388 // Do nothing.
8389 break;
8390 }
8391 }
8392
Mike Stump11289f42009-09-09 15:08:12 +00008393 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008394 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008395 if (HasBetterConversion)
8396 return true;
8397
Douglas Gregora1f013e2008-11-07 22:36:19 +00008398 // -- the context is an initialization by user-defined conversion
8399 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8400 // from the return type of F1 to the destination type (i.e.,
8401 // the type of the entity being initialized) is a better
8402 // conversion sequence than the standard conversion sequence
8403 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008404 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008405 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008406 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008407 // First check whether we prefer one of the conversion functions over the
8408 // other. This only distinguishes the results in non-standard, extension
8409 // cases such as the conversion from a lambda closure type to a function
8410 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008411 ImplicitConversionSequence::CompareKind Result =
8412 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8413 if (Result == ImplicitConversionSequence::Indistinguishable)
8414 Result = CompareStandardConversionSequences(S,
8415 Cand1.FinalConversion,
8416 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008417
Richard Smithec2748a2014-05-17 04:36:39 +00008418 if (Result != ImplicitConversionSequence::Indistinguishable)
8419 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008420
8421 // FIXME: Compare kind of reference binding if conversion functions
8422 // convert to a reference type used in direct reference binding, per
8423 // C++14 [over.match.best]p1 section 2 bullet 3.
8424 }
8425
8426 // -- F1 is a non-template function and F2 is a function template
8427 // specialization, or, if not that,
8428 bool Cand1IsSpecialization = Cand1.Function &&
8429 Cand1.Function->getPrimaryTemplate();
8430 bool Cand2IsSpecialization = Cand2.Function &&
8431 Cand2.Function->getPrimaryTemplate();
8432 if (Cand1IsSpecialization != Cand2IsSpecialization)
8433 return Cand2IsSpecialization;
8434
8435 // -- F1 and F2 are function template specializations, and the function
8436 // template for F1 is more specialized than the template for F2
8437 // according to the partial ordering rules described in 14.5.5.2, or,
8438 // if not that,
8439 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8440 if (FunctionTemplateDecl *BetterTemplate
8441 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8442 Cand2.Function->getPrimaryTemplate(),
8443 Loc,
8444 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8445 : TPOC_Call,
8446 Cand1.ExplicitCallArguments,
8447 Cand2.ExplicitCallArguments))
8448 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008449 }
8450
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008451 // Check for enable_if value-based overload resolution.
8452 if (Cand1.Function && Cand2.Function &&
8453 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8454 Cand2.Function->hasAttr<EnableIfAttr>())) {
8455 // FIXME: The next several lines are just
8456 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8457 // instead of reverse order which is how they're stored in the AST.
8458 AttrVec Cand1Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008459 if (Cand1.Function->hasAttrs()) {
8460 Cand1Attrs = Cand1.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008461 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8462 IsNotEnableIfAttr),
8463 Cand1Attrs.end());
8464 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008465 }
8466
8467 AttrVec Cand2Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008468 if (Cand2.Function->hasAttrs()) {
8469 Cand2Attrs = Cand2.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008470 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8471 IsNotEnableIfAttr),
8472 Cand2Attrs.end());
8473 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008474 }
Richard Smith9516eee2014-05-17 02:21:47 +00008475
8476 // Candidate 1 is better if it has strictly more attributes and
8477 // the common sequence is identical.
8478 if (Cand1Attrs.size() <= Cand2Attrs.size())
8479 return false;
8480
8481 auto Cand1I = Cand1Attrs.begin();
8482 for (auto &Cand2A : Cand2Attrs) {
8483 auto &Cand1A = *Cand1I++;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008484 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Richard Smith9516eee2014-05-17 02:21:47 +00008485 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8486 S.getASTContext(), true);
8487 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8488 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008489 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008490 return false;
8491 }
Richard Smith9516eee2014-05-17 02:21:47 +00008492
8493 return true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008494 }
8495
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008496 return false;
8497}
8498
Mike Stump11289f42009-09-09 15:08:12 +00008499/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008500/// within an overload candidate set.
8501///
James Dennettffad8b72012-06-22 08:10:18 +00008502/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008503/// which overload resolution occurs.
8504///
James Dennettffad8b72012-06-22 08:10:18 +00008505/// \param Best If overload resolution was successful or found a deleted
8506/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008507///
8508/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008509OverloadingResult
8510OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008511 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008512 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008513 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008514 Best = end();
8515 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8516 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008517 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008518 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008519 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008520 }
8521
8522 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008523 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008524 return OR_No_Viable_Function;
8525
8526 // Make sure that this function is better than every other viable
8527 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008528 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008529 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008530 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008531 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008532 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008533 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008534 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008535 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008536 }
Mike Stump11289f42009-09-09 15:08:12 +00008537
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008538 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008539 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008540 (Best->Function->isDeleted() ||
8541 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008542 return OR_Deleted;
8543
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008544 return OR_Success;
8545}
8546
John McCall53262c92010-01-12 02:15:36 +00008547namespace {
8548
8549enum OverloadCandidateKind {
8550 oc_function,
8551 oc_method,
8552 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008553 oc_function_template,
8554 oc_method_template,
8555 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008556 oc_implicit_default_constructor,
8557 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008558 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008559 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008560 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008561 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008562};
8563
John McCalle1ac8d12010-01-13 00:25:19 +00008564OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8565 FunctionDecl *Fn,
8566 std::string &Description) {
8567 bool isTemplate = false;
8568
8569 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8570 isTemplate = true;
8571 Description = S.getTemplateArgumentBindingsText(
8572 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8573 }
John McCallfd0b2f82010-01-06 09:43:14 +00008574
8575 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008576 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008577 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008578
Sebastian Redl08905022011-02-05 19:23:19 +00008579 if (Ctor->getInheritedConstructor())
8580 return oc_implicit_inherited_constructor;
8581
Alexis Hunt119c10e2011-05-25 23:16:36 +00008582 if (Ctor->isDefaultConstructor())
8583 return oc_implicit_default_constructor;
8584
8585 if (Ctor->isMoveConstructor())
8586 return oc_implicit_move_constructor;
8587
8588 assert(Ctor->isCopyConstructor() &&
8589 "unexpected sort of implicit constructor");
8590 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008591 }
8592
8593 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8594 // This actually gets spelled 'candidate function' for now, but
8595 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008596 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008597 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008598
Alexis Hunt119c10e2011-05-25 23:16:36 +00008599 if (Meth->isMoveAssignmentOperator())
8600 return oc_implicit_move_assignment;
8601
Douglas Gregor12695102012-02-10 08:36:38 +00008602 if (Meth->isCopyAssignmentOperator())
8603 return oc_implicit_copy_assignment;
8604
8605 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8606 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008607 }
8608
John McCalle1ac8d12010-01-13 00:25:19 +00008609 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008610}
8611
Larisse Voufo98b20f12013-07-19 23:00:19 +00008612void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008613 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8614 if (!Ctor) return;
8615
8616 Ctor = Ctor->getInheritedConstructor();
8617 if (!Ctor) return;
8618
8619 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8620}
8621
John McCall53262c92010-01-12 02:15:36 +00008622} // end anonymous namespace
8623
8624// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008625void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008626 std::string FnDesc;
8627 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008628 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8629 << (unsigned) K << FnDesc;
8630 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8631 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008632 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008633}
8634
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008635// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008636// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008637void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008638 assert(OverloadedExpr->getType() == Context.OverloadTy);
8639
8640 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8641 OverloadExpr *OvlExpr = Ovl.Expression;
8642
8643 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8644 IEnd = OvlExpr->decls_end();
8645 I != IEnd; ++I) {
8646 if (FunctionTemplateDecl *FunTmpl =
8647 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008648 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008649 } else if (FunctionDecl *Fun
8650 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008651 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008652 }
8653 }
8654}
8655
John McCall0d1da222010-01-12 00:44:57 +00008656/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8657/// "lead" diagnostic; it will be given two arguments, the source and
8658/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008659void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8660 Sema &S,
8661 SourceLocation CaretLoc,
8662 const PartialDiagnostic &PDiag) const {
8663 S.Diag(CaretLoc, PDiag)
8664 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008665 // FIXME: The note limiting machinery is borrowed from
8666 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8667 // refactoring here.
8668 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8669 unsigned CandsShown = 0;
8670 AmbiguousConversionSequence::const_iterator I, E;
8671 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8672 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8673 break;
8674 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008675 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008676 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008677 if (I != E)
8678 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008679}
8680
Richard Smith17c00b42014-11-12 01:24:00 +00008681static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8682 unsigned I) {
John McCall6a61b522010-01-13 09:16:55 +00008683 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8684 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008685 assert(Cand->Function && "for now, candidate must be a function");
8686 FunctionDecl *Fn = Cand->Function;
8687
8688 // There's a conversion slot for the object argument if this is a
8689 // non-constructor method. Note that 'I' corresponds the
8690 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008691 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008692 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008693 if (I == 0)
8694 isObjectArgument = true;
8695 else
8696 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008697 }
8698
John McCalle1ac8d12010-01-13 00:25:19 +00008699 std::string FnDesc;
8700 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8701
John McCall6a61b522010-01-13 09:16:55 +00008702 Expr *FromExpr = Conv.Bad.FromExpr;
8703 QualType FromTy = Conv.Bad.getFromType();
8704 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008705
John McCallfb7ad0f2010-02-02 02:42:52 +00008706 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008707 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008708 Expr *E = FromExpr->IgnoreParens();
8709 if (isa<UnaryOperator>(E))
8710 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008711 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008712
8713 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8714 << (unsigned) FnKind << FnDesc
8715 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8716 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008717 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008718 return;
8719 }
8720
John McCall6d174642010-01-23 08:10:49 +00008721 // Do some hand-waving analysis to see if the non-viability is due
8722 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008723 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8724 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8725 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8726 CToTy = RT->getPointeeType();
8727 else {
8728 // TODO: detect and diagnose the full richness of const mismatches.
8729 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8730 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8731 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8732 }
8733
8734 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8735 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008736 Qualifiers FromQs = CFromTy.getQualifiers();
8737 Qualifiers ToQs = CToTy.getQualifiers();
8738
8739 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8740 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8741 << (unsigned) FnKind << FnDesc
8742 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8743 << FromTy
8744 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8745 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008746 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008747 return;
8748 }
8749
John McCall31168b02011-06-15 23:02:42 +00008750 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008751 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008752 << (unsigned) FnKind << FnDesc
8753 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8754 << FromTy
8755 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8756 << (unsigned) isObjectArgument << I+1;
8757 MaybeEmitInheritedConstructorNote(S, Fn);
8758 return;
8759 }
8760
Douglas Gregoraec25842011-04-26 23:16:46 +00008761 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8762 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8763 << (unsigned) FnKind << FnDesc
8764 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8765 << FromTy
8766 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8767 << (unsigned) isObjectArgument << I+1;
8768 MaybeEmitInheritedConstructorNote(S, Fn);
8769 return;
8770 }
8771
John McCall47000992010-01-14 03:28:57 +00008772 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8773 assert(CVR && "unexpected qualifiers mismatch");
8774
8775 if (isObjectArgument) {
8776 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8777 << (unsigned) FnKind << FnDesc
8778 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8779 << FromTy << (CVR - 1);
8780 } else {
8781 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8782 << (unsigned) FnKind << FnDesc
8783 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8784 << FromTy << (CVR - 1) << I+1;
8785 }
Sebastian Redl08905022011-02-05 19:23:19 +00008786 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008787 return;
8788 }
8789
Sebastian Redla72462c2011-09-24 17:48:32 +00008790 // Special diagnostic for failure to convert an initializer list, since
8791 // telling the user that it has type void is not useful.
8792 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8793 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8794 << (unsigned) FnKind << FnDesc
8795 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8796 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8797 MaybeEmitInheritedConstructorNote(S, Fn);
8798 return;
8799 }
8800
John McCall6d174642010-01-23 08:10:49 +00008801 // Diagnose references or pointers to incomplete types differently,
8802 // since it's far from impossible that the incompleteness triggered
8803 // the failure.
8804 QualType TempFromTy = FromTy.getNonReferenceType();
8805 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8806 TempFromTy = PTy->getPointeeType();
8807 if (TempFromTy->isIncompleteType()) {
8808 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8809 << (unsigned) FnKind << FnDesc
8810 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8811 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008812 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008813 return;
8814 }
8815
Douglas Gregor56f2e342010-06-30 23:01:39 +00008816 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008817 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008818 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8819 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8820 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8821 FromPtrTy->getPointeeType()) &&
8822 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8823 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008824 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008825 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008826 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008827 }
8828 } else if (const ObjCObjectPointerType *FromPtrTy
8829 = FromTy->getAs<ObjCObjectPointerType>()) {
8830 if (const ObjCObjectPointerType *ToPtrTy
8831 = ToTy->getAs<ObjCObjectPointerType>())
8832 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8833 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8834 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8835 FromPtrTy->getPointeeType()) &&
8836 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008837 BaseToDerivedConversion = 2;
8838 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008839 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8840 !FromTy->isIncompleteType() &&
8841 !ToRefTy->getPointeeType()->isIncompleteType() &&
8842 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8843 BaseToDerivedConversion = 3;
8844 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8845 ToTy.getNonReferenceType().getCanonicalType() ==
8846 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008847 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8848 << (unsigned) FnKind << FnDesc
8849 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8850 << (unsigned) isObjectArgument << I + 1;
8851 MaybeEmitInheritedConstructorNote(S, Fn);
8852 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008853 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008854 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008855
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008856 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008857 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008858 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008859 << (unsigned) FnKind << FnDesc
8860 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008861 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008862 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008863 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008864 return;
8865 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008866
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008867 if (isa<ObjCObjectPointerType>(CFromTy) &&
8868 isa<PointerType>(CToTy)) {
8869 Qualifiers FromQs = CFromTy.getQualifiers();
8870 Qualifiers ToQs = CToTy.getQualifiers();
8871 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8872 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8873 << (unsigned) FnKind << FnDesc
8874 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8875 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8876 MaybeEmitInheritedConstructorNote(S, Fn);
8877 return;
8878 }
8879 }
8880
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008881 // Emit the generic diagnostic and, optionally, add the hints to it.
8882 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8883 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008884 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008885 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8886 << (unsigned) (Cand->Fix.Kind);
8887
8888 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008889 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8890 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008891 FDiag << *HI;
8892 S.Diag(Fn->getLocation(), FDiag);
8893
Sebastian Redl08905022011-02-05 19:23:19 +00008894 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008895}
8896
Larisse Voufo98b20f12013-07-19 23:00:19 +00008897/// Additional arity mismatch diagnosis specific to a function overload
8898/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8899/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008900static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8901 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008902 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008903 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008904
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008905 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008906 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008907 // right number of arguments, because only overloaded operators have
8908 // the weird behavior of overloading member and non-member functions.
8909 // Just don't report anything.
8910 if (Fn->isInvalidDecl() &&
8911 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008912 return true;
8913
8914 if (NumArgs < MinParams) {
8915 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8916 (Cand->FailureKind == ovl_fail_bad_deduction &&
8917 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8918 } else {
8919 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8920 (Cand->FailureKind == ovl_fail_bad_deduction &&
8921 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8922 }
8923
8924 return false;
8925}
8926
8927/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008928static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008929 assert(isa<FunctionDecl>(D) &&
8930 "The templated declaration should at least be a function"
8931 " when diagnosing bad template argument deduction due to too many"
8932 " or too few arguments");
8933
8934 FunctionDecl *Fn = cast<FunctionDecl>(D);
8935
8936 // TODO: treat calls to a missing default constructor as a special case
8937 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8938 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008939
John McCall6a61b522010-01-13 09:16:55 +00008940 // at least / at most / exactly
8941 unsigned mode, modeCount;
8942 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008943 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8944 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008945 mode = 0; // "at least"
8946 else
8947 mode = 2; // "exactly"
8948 modeCount = MinParams;
8949 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008950 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008951 mode = 1; // "at most"
8952 else
8953 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008954 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008955 }
8956
8957 std::string Description;
8958 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8959
Richard Smith10ff50d2012-05-11 05:16:41 +00008960 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8961 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00008962 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8963 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00008964 else
8965 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00008966 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8967 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008968 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008969}
8970
Larisse Voufo98b20f12013-07-19 23:00:19 +00008971/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00008972static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8973 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008974 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8975 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8976}
Larisse Voufo47c08452013-07-19 22:53:23 +00008977
Richard Smith17c00b42014-11-12 01:24:00 +00008978static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008979 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8980 return FD->getDescribedFunctionTemplate();
8981 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8982 return RD->getDescribedClassTemplate();
8983
8984 llvm_unreachable("Unsupported: Getting the described template declaration"
8985 " for bad deduction diagnosis");
8986}
8987
8988/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00008989static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8990 DeductionFailureInfo &DeductionFailure,
8991 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008992 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008993 NamedDecl *ParamD;
8994 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8995 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8996 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00008997 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00008998 case Sema::TDK_Success:
8999 llvm_unreachable("TDK_success while diagnosing bad deduction");
9000
9001 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009002 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009003 S.Diag(Templated->getLocation(),
9004 diag::note_ovl_candidate_incomplete_deduction)
9005 << ParamD->getDeclName();
9006 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009007 return;
9008 }
9009
John McCall42d7d192010-08-05 09:05:08 +00009010 case Sema::TDK_Underqualified: {
9011 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9012 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9013
Larisse Voufo98b20f12013-07-19 23:00:19 +00009014 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009015
9016 // Param will have been canonicalized, but it should just be a
9017 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009018 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009019 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009020 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009021 assert(S.Context.hasSameType(Param, NonCanonParam));
9022
9023 // Arg has also been canonicalized, but there's nothing we can do
9024 // about that. It also doesn't matter as much, because it won't
9025 // have any template parameters in it (because deduction isn't
9026 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009027 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009028
Larisse Voufo98b20f12013-07-19 23:00:19 +00009029 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9030 << ParamD->getDeclName() << Arg << NonCanonParam;
9031 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009032 return;
9033 }
9034
9035 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009036 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009037 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009038 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009039 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009040 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009041 which = 1;
9042 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009043 which = 2;
9044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009045
Larisse Voufo98b20f12013-07-19 23:00:19 +00009046 S.Diag(Templated->getLocation(),
9047 diag::note_ovl_candidate_inconsistent_deduction)
9048 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9049 << *DeductionFailure.getSecondArg();
9050 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009051 return;
9052 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009053
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009054 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009055 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009056 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009057 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009058 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009059 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009060 else {
9061 int index = 0;
9062 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9063 index = TTP->getIndex();
9064 else if (NonTypeTemplateParmDecl *NTTP
9065 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9066 index = NTTP->getIndex();
9067 else
9068 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009069 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009070 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009071 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009072 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009073 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009074 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009075
Douglas Gregor02eb4832010-05-08 18:13:28 +00009076 case Sema::TDK_TooManyArguments:
9077 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009078 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009079 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009080
9081 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009082 S.Diag(Templated->getLocation(),
9083 diag::note_ovl_candidate_instantiation_depth);
9084 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009085 return;
9086
9087 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009088 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009089 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009090 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009091 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009092 TemplateArgString = " ";
9093 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009094 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009095 }
9096
Richard Smith6f8d2c62012-05-09 05:17:00 +00009097 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009098 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009099 if (PDiag && PDiag->second.getDiagID() ==
9100 diag::err_typename_nested_not_found_enable_if) {
9101 // FIXME: Use the source range of the condition, and the fully-qualified
9102 // name of the enable_if template. These are both present in PDiag.
9103 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9104 << "'enable_if'" << TemplateArgString;
9105 return;
9106 }
9107
Richard Smith9ca64612012-05-07 09:03:25 +00009108 // Format the SFINAE diagnostic into the argument string.
9109 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9110 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009111 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009112 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009113 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009114 SFINAEArgString = ": ";
9115 R = SourceRange(PDiag->first, PDiag->first);
9116 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9117 }
9118
Larisse Voufo98b20f12013-07-19 23:00:19 +00009119 S.Diag(Templated->getLocation(),
9120 diag::note_ovl_candidate_substitution_failure)
9121 << TemplateArgString << SFINAEArgString << R;
9122 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009123 return;
9124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009125
Richard Smith8c6eeb92013-01-31 04:03:12 +00009126 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009127 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9128 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009129 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009130 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009131 return;
9132 }
9133
Richard Trieue3732352013-04-08 21:11:40 +00009134 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009135 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009136 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9137 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009138 if (FirstTA.getKind() == TemplateArgument::Template &&
9139 SecondTA.getKind() == TemplateArgument::Template) {
9140 TemplateName FirstTN = FirstTA.getAsTemplate();
9141 TemplateName SecondTN = SecondTA.getAsTemplate();
9142 if (FirstTN.getKind() == TemplateName::Template &&
9143 SecondTN.getKind() == TemplateName::Template) {
9144 if (FirstTN.getAsTemplateDecl()->getName() ==
9145 SecondTN.getAsTemplateDecl()->getName()) {
9146 // FIXME: This fixes a bad diagnostic where both templates are named
9147 // the same. This particular case is a bit difficult since:
9148 // 1) It is passed as a string to the diagnostic printer.
9149 // 2) The diagnostic printer only attempts to find a better
9150 // name for types, not decls.
9151 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009152 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009153 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9154 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9155 return;
9156 }
9157 }
9158 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00009159 // FIXME: For generic lambda parameters, check if the function is a lambda
9160 // call operator, and if so, emit a prettier and more informative
9161 // diagnostic that mentions 'auto' and lambda in addition to
9162 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009163 S.Diag(Templated->getLocation(),
9164 diag::note_ovl_candidate_non_deduced_mismatch)
9165 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009166 return;
Richard Trieue3732352013-04-08 21:11:40 +00009167 }
John McCall8b9ed552010-02-01 18:53:26 +00009168 // TODO: diagnose these individually, then kill off
9169 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009170 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009171 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9172 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009173 return;
9174 }
9175}
9176
Larisse Voufo98b20f12013-07-19 23:00:19 +00009177/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009178static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9179 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009180 unsigned TDK = Cand->DeductionFailure.Result;
9181 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9182 if (CheckArityMismatch(S, Cand, NumArgs))
9183 return;
9184 }
9185 DiagnoseBadDeduction(S, Cand->Function, // pattern
9186 Cand->DeductionFailure, NumArgs);
9187}
9188
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009189/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009190static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009191 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9192 FunctionDecl *Callee = Cand->Function;
9193
9194 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9195 CalleeTarget = S.IdentifyCUDATarget(Callee);
9196
9197 std::string FnDesc;
9198 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9199
9200 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009201 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9202
9203 // This could be an implicit constructor for which we could not infer the
9204 // target due to a collsion. Diagnose that case.
9205 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9206 if (Meth != nullptr && Meth->isImplicit()) {
9207 CXXRecordDecl *ParentClass = Meth->getParent();
9208 Sema::CXXSpecialMember CSM;
9209
9210 switch (FnKind) {
9211 default:
9212 return;
9213 case oc_implicit_default_constructor:
9214 CSM = Sema::CXXDefaultConstructor;
9215 break;
9216 case oc_implicit_copy_constructor:
9217 CSM = Sema::CXXCopyConstructor;
9218 break;
9219 case oc_implicit_move_constructor:
9220 CSM = Sema::CXXMoveConstructor;
9221 break;
9222 case oc_implicit_copy_assignment:
9223 CSM = Sema::CXXCopyAssignment;
9224 break;
9225 case oc_implicit_move_assignment:
9226 CSM = Sema::CXXMoveAssignment;
9227 break;
9228 };
9229
9230 bool ConstRHS = false;
9231 if (Meth->getNumParams()) {
9232 if (const ReferenceType *RT =
9233 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9234 ConstRHS = RT->getPointeeType().isConstQualified();
9235 }
9236 }
9237
9238 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9239 /* ConstRHS */ ConstRHS,
9240 /* Diagnose */ true);
9241 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009242}
9243
Richard Smith17c00b42014-11-12 01:24:00 +00009244static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009245 FunctionDecl *Callee = Cand->Function;
9246 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9247
9248 S.Diag(Callee->getLocation(),
9249 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9250 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9251}
9252
John McCall8b9ed552010-02-01 18:53:26 +00009253/// Generates a 'note' diagnostic for an overload candidate. We've
9254/// already generated a primary error at the call site.
9255///
9256/// It really does need to be a single diagnostic with its caret
9257/// pointed at the candidate declaration. Yes, this creates some
9258/// major challenges of technical writing. Yes, this makes pointing
9259/// out problems with specific arguments quite awkward. It's still
9260/// better than generating twenty screens of text for every failed
9261/// overload.
9262///
9263/// It would be great to be able to express per-candidate problems
9264/// more richly for those diagnostic clients that cared, but we'd
9265/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009266static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9267 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009268 FunctionDecl *Fn = Cand->Function;
9269
John McCall12f97bc2010-01-08 04:41:39 +00009270 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009271 if (Cand->Viable && (Fn->isDeleted() ||
9272 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009273 std::string FnDesc;
9274 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009275
9276 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009277 << FnKind << FnDesc
9278 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009279 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009280 return;
John McCall12f97bc2010-01-08 04:41:39 +00009281 }
9282
John McCalle1ac8d12010-01-13 00:25:19 +00009283 // We don't really have anything else to say about viable candidates.
9284 if (Cand->Viable) {
9285 S.NoteOverloadCandidate(Fn);
9286 return;
9287 }
John McCall0d1da222010-01-12 00:44:57 +00009288
John McCall6a61b522010-01-13 09:16:55 +00009289 switch (Cand->FailureKind) {
9290 case ovl_fail_too_many_arguments:
9291 case ovl_fail_too_few_arguments:
9292 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009293
John McCall6a61b522010-01-13 09:16:55 +00009294 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009295 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009296
John McCall578a1f82014-12-14 01:46:53 +00009297 case ovl_fail_illegal_constructor: {
9298 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9299 << (Fn->getPrimaryTemplate() ? 1 : 0);
9300 MaybeEmitInheritedConstructorNote(S, Fn);
9301 return;
9302 }
9303
John McCallfe796dd2010-01-23 05:17:32 +00009304 case ovl_fail_trivial_conversion:
9305 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009306 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009307 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009308
John McCall65eb8792010-02-25 01:37:24 +00009309 case ovl_fail_bad_conversion: {
9310 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009311 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009312 if (Cand->Conversions[I].isBad())
9313 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009314
John McCall6a61b522010-01-13 09:16:55 +00009315 // FIXME: this currently happens when we're called from SemaInit
9316 // when user-conversion overload fails. Figure out how to handle
9317 // those conditions and diagnose them well.
9318 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009319 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009320
9321 case ovl_fail_bad_target:
9322 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009323
9324 case ovl_fail_enable_if:
9325 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009326 }
John McCalld3224162010-01-08 00:58:21 +00009327}
9328
Richard Smith17c00b42014-11-12 01:24:00 +00009329static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009330 // Desugar the type of the surrogate down to a function type,
9331 // retaining as many typedefs as possible while still showing
9332 // the function type (and, therefore, its parameter types).
9333 QualType FnType = Cand->Surrogate->getConversionType();
9334 bool isLValueReference = false;
9335 bool isRValueReference = false;
9336 bool isPointer = false;
9337 if (const LValueReferenceType *FnTypeRef =
9338 FnType->getAs<LValueReferenceType>()) {
9339 FnType = FnTypeRef->getPointeeType();
9340 isLValueReference = true;
9341 } else if (const RValueReferenceType *FnTypeRef =
9342 FnType->getAs<RValueReferenceType>()) {
9343 FnType = FnTypeRef->getPointeeType();
9344 isRValueReference = true;
9345 }
9346 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9347 FnType = FnTypePtr->getPointeeType();
9348 isPointer = true;
9349 }
9350 // Desugar down to a function type.
9351 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9352 // Reconstruct the pointer/reference as appropriate.
9353 if (isPointer) FnType = S.Context.getPointerType(FnType);
9354 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9355 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9356
9357 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9358 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009359 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009360}
9361
Richard Smith17c00b42014-11-12 01:24:00 +00009362static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9363 SourceLocation OpLoc,
9364 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009365 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009366 std::string TypeStr("operator");
9367 TypeStr += Opc;
9368 TypeStr += "(";
9369 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009370 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009371 TypeStr += ")";
9372 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9373 } else {
9374 TypeStr += ", ";
9375 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9376 TypeStr += ")";
9377 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9378 }
9379}
9380
Richard Smith17c00b42014-11-12 01:24:00 +00009381static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9382 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009383 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009384 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9385 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009386 if (ICS.isBad()) break; // all meaningless after first invalid
9387 if (!ICS.isAmbiguous()) continue;
9388
John McCall5c32be02010-08-24 20:38:10 +00009389 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009390 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009391 }
9392}
9393
Larisse Voufo98b20f12013-07-19 23:00:19 +00009394static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009395 if (Cand->Function)
9396 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009397 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009398 return Cand->Surrogate->getLocation();
9399 return SourceLocation();
9400}
9401
Larisse Voufo98b20f12013-07-19 23:00:19 +00009402static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009403 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009404 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009405 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009406
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009407 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009408 case Sema::TDK_Incomplete:
9409 return 1;
9410
9411 case Sema::TDK_Underqualified:
9412 case Sema::TDK_Inconsistent:
9413 return 2;
9414
9415 case Sema::TDK_SubstitutionFailure:
9416 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009417 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009418 return 3;
9419
9420 case Sema::TDK_InstantiationDepth:
9421 case Sema::TDK_FailedOverloadResolution:
9422 return 4;
9423
9424 case Sema::TDK_InvalidExplicitArguments:
9425 return 5;
9426
9427 case Sema::TDK_TooManyArguments:
9428 case Sema::TDK_TooFewArguments:
9429 return 6;
9430 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009431 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009432}
9433
Richard Smith17c00b42014-11-12 01:24:00 +00009434namespace {
John McCallad2587a2010-01-12 00:48:53 +00009435struct CompareOverloadCandidatesForDisplay {
9436 Sema &S;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009437 size_t NumArgs;
9438
9439 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9440 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009441
9442 bool operator()(const OverloadCandidate *L,
9443 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009444 // Fast-path this check.
9445 if (L == R) return false;
9446
John McCall12f97bc2010-01-08 04:41:39 +00009447 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009448 if (L->Viable) {
9449 if (!R->Viable) return true;
9450
9451 // TODO: introduce a tri-valued comparison for overload
9452 // candidates. Would be more worthwhile if we had a sort
9453 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009454 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9455 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009456 } else if (R->Viable)
9457 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009458
John McCall3712d9e2010-01-15 23:32:50 +00009459 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009460
John McCall3712d9e2010-01-15 23:32:50 +00009461 // Criteria by which we can sort non-viable candidates:
9462 if (!L->Viable) {
9463 // 1. Arity mismatches come after other candidates.
9464 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009465 L->FailureKind == ovl_fail_too_few_arguments) {
9466 if (R->FailureKind == ovl_fail_too_many_arguments ||
9467 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009468 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9469 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9470 if (LDist == RDist) {
9471 if (L->FailureKind == R->FailureKind)
9472 // Sort non-surrogates before surrogates.
9473 return !L->IsSurrogate && R->IsSurrogate;
9474 // Sort candidates requiring fewer parameters than there were
9475 // arguments given after candidates requiring more parameters
9476 // than there were arguments given.
9477 return L->FailureKind == ovl_fail_too_many_arguments;
9478 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009479 return LDist < RDist;
9480 }
John McCall3712d9e2010-01-15 23:32:50 +00009481 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009482 }
John McCall3712d9e2010-01-15 23:32:50 +00009483 if (R->FailureKind == ovl_fail_too_many_arguments ||
9484 R->FailureKind == ovl_fail_too_few_arguments)
9485 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009486
John McCallfe796dd2010-01-23 05:17:32 +00009487 // 2. Bad conversions come first and are ordered by the number
9488 // of bad conversions and quality of good conversions.
9489 if (L->FailureKind == ovl_fail_bad_conversion) {
9490 if (R->FailureKind != ovl_fail_bad_conversion)
9491 return true;
9492
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009493 // The conversion that can be fixed with a smaller number of changes,
9494 // comes first.
9495 unsigned numLFixes = L->Fix.NumConversionsFixed;
9496 unsigned numRFixes = R->Fix.NumConversionsFixed;
9497 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9498 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009499 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009500 if (numLFixes < numRFixes)
9501 return true;
9502 else
9503 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009504 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009505
John McCallfe796dd2010-01-23 05:17:32 +00009506 // If there's any ordering between the defined conversions...
9507 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009508 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009509
9510 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009511 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009512 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009513 switch (CompareImplicitConversionSequences(S,
9514 L->Conversions[I],
9515 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009516 case ImplicitConversionSequence::Better:
9517 leftBetter++;
9518 break;
9519
9520 case ImplicitConversionSequence::Worse:
9521 leftBetter--;
9522 break;
9523
9524 case ImplicitConversionSequence::Indistinguishable:
9525 break;
9526 }
9527 }
9528 if (leftBetter > 0) return true;
9529 if (leftBetter < 0) return false;
9530
9531 } else if (R->FailureKind == ovl_fail_bad_conversion)
9532 return false;
9533
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009534 if (L->FailureKind == ovl_fail_bad_deduction) {
9535 if (R->FailureKind != ovl_fail_bad_deduction)
9536 return true;
9537
9538 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9539 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009540 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009541 } else if (R->FailureKind == ovl_fail_bad_deduction)
9542 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009543
John McCall3712d9e2010-01-15 23:32:50 +00009544 // TODO: others?
9545 }
9546
9547 // Sort everything else by location.
9548 SourceLocation LLoc = GetLocationForCandidate(L);
9549 SourceLocation RLoc = GetLocationForCandidate(R);
9550
9551 // Put candidates without locations (e.g. builtins) at the end.
9552 if (LLoc.isInvalid()) return false;
9553 if (RLoc.isInvalid()) return true;
9554
9555 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009556 }
9557};
Richard Smith17c00b42014-11-12 01:24:00 +00009558}
John McCall12f97bc2010-01-08 04:41:39 +00009559
John McCallfe796dd2010-01-23 05:17:32 +00009560/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009561/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009562static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9563 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009564 assert(!Cand->Viable);
9565
9566 // Don't do anything on failures other than bad conversion.
9567 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9568
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009569 // We only want the FixIts if all the arguments can be corrected.
9570 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009571 // Use a implicit copy initialization to check conversion fixes.
9572 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009573
John McCallfe796dd2010-01-23 05:17:32 +00009574 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009575 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009576 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009577 while (true) {
9578 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9579 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009580 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009581 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009582 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009583 }
John McCallfe796dd2010-01-23 05:17:32 +00009584 }
9585
9586 if (ConvIdx == ConvCount)
9587 return;
9588
John McCall65eb8792010-02-25 01:37:24 +00009589 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9590 "remaining conversion is initialized?");
9591
Douglas Gregoradc7a702010-04-16 17:45:54 +00009592 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009593 // operation somehow.
9594 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009595
9596 const FunctionProtoType* Proto;
9597 unsigned ArgIdx = ConvIdx;
9598
9599 if (Cand->IsSurrogate) {
9600 QualType ConvType
9601 = Cand->Surrogate->getConversionType().getNonReferenceType();
9602 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9603 ConvType = ConvPtrType->getPointeeType();
9604 Proto = ConvType->getAs<FunctionProtoType>();
9605 ArgIdx--;
9606 } else if (Cand->Function) {
9607 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9608 if (isa<CXXMethodDecl>(Cand->Function) &&
9609 !isa<CXXConstructorDecl>(Cand->Function))
9610 ArgIdx--;
9611 } else {
9612 // Builtin binary operator with a bad first conversion.
9613 assert(ConvCount <= 3);
9614 for (; ConvIdx != ConvCount; ++ConvIdx)
9615 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009616 = TryCopyInitialization(S, Args[ConvIdx],
9617 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009618 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009619 /*InOverloadResolution*/ true,
9620 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009621 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009622 return;
9623 }
9624
9625 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009626 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009627 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009628 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009629 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9630 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9631 /*InOverloadResolution=*/true,
9632 /*AllowObjCWritebackConversion=*/
9633 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009634 // Store the FixIt in the candidate if it exists.
9635 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009636 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009637 }
John McCallfe796dd2010-01-23 05:17:32 +00009638 else
9639 Cand->Conversions[ConvIdx].setEllipsis();
9640 }
9641}
9642
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009643/// PrintOverloadCandidates - When overload resolution fails, prints
9644/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009645/// set.
John McCall5c32be02010-08-24 20:38:10 +00009646void OverloadCandidateSet::NoteCandidates(Sema &S,
9647 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009648 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009649 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009650 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009651 // Sort the candidates by viability and position. Sorting directly would
9652 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009653 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009654 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9655 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009656 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009657 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009658 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009659 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009660 if (Cand->Function || Cand->IsSurrogate)
9661 Cands.push_back(Cand);
9662 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9663 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009664 }
9665 }
9666
John McCallad2587a2010-01-12 00:48:53 +00009667 std::sort(Cands.begin(), Cands.end(),
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009668 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009669
John McCall0d1da222010-01-12 00:44:57 +00009670 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009671
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009672 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009673 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009674 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009675 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9676 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009677
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009678 // Set an arbitrary limit on the number of candidate functions we'll spam
9679 // the user with. FIXME: This limit should depend on details of the
9680 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009681 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009682 break;
9683 }
9684 ++CandsShown;
9685
John McCalld3224162010-01-08 00:58:21 +00009686 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009687 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009688 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009689 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009690 else {
9691 assert(Cand->Viable &&
9692 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009693 // Generally we only see ambiguities including viable builtin
9694 // operators if overload resolution got screwed up by an
9695 // ambiguous user-defined conversion.
9696 //
9697 // FIXME: It's quite possible for different conversions to see
9698 // different ambiguities, though.
9699 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009700 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009701 ReportedAmbiguousConversions = true;
9702 }
John McCalld3224162010-01-08 00:58:21 +00009703
John McCall0d1da222010-01-12 00:44:57 +00009704 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009705 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009706 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009707 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009708
9709 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009710 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009711}
9712
Larisse Voufo98b20f12013-07-19 23:00:19 +00009713static SourceLocation
9714GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9715 return Cand->Specialization ? Cand->Specialization->getLocation()
9716 : SourceLocation();
9717}
9718
Richard Smith17c00b42014-11-12 01:24:00 +00009719namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009720struct CompareTemplateSpecCandidatesForDisplay {
9721 Sema &S;
9722 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9723
9724 bool operator()(const TemplateSpecCandidate *L,
9725 const TemplateSpecCandidate *R) {
9726 // Fast-path this check.
9727 if (L == R)
9728 return false;
9729
9730 // Assuming that both candidates are not matches...
9731
9732 // Sort by the ranking of deduction failures.
9733 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9734 return RankDeductionFailure(L->DeductionFailure) <
9735 RankDeductionFailure(R->DeductionFailure);
9736
9737 // Sort everything else by location.
9738 SourceLocation LLoc = GetLocationForCandidate(L);
9739 SourceLocation RLoc = GetLocationForCandidate(R);
9740
9741 // Put candidates without locations (e.g. builtins) at the end.
9742 if (LLoc.isInvalid())
9743 return false;
9744 if (RLoc.isInvalid())
9745 return true;
9746
9747 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9748 }
9749};
Richard Smith17c00b42014-11-12 01:24:00 +00009750}
Larisse Voufo98b20f12013-07-19 23:00:19 +00009751
9752/// Diagnose a template argument deduction failure.
9753/// We are treating these failures as overload failures due to bad
9754/// deductions.
9755void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9756 DiagnoseBadDeduction(S, Specialization, // pattern
9757 DeductionFailure, /*NumArgs=*/0);
9758}
9759
9760void TemplateSpecCandidateSet::destroyCandidates() {
9761 for (iterator i = begin(), e = end(); i != e; ++i) {
9762 i->DeductionFailure.Destroy();
9763 }
9764}
9765
9766void TemplateSpecCandidateSet::clear() {
9767 destroyCandidates();
9768 Candidates.clear();
9769}
9770
9771/// NoteCandidates - When no template specialization match is found, prints
9772/// diagnostic messages containing the non-matching specializations that form
9773/// the candidate set.
9774/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9775/// OCD == OCD_AllCandidates and Cand->Viable == false.
9776void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9777 // Sort the candidates by position (assuming no candidate is a match).
9778 // Sorting directly would be prohibitive, so we make a set of pointers
9779 // and sort those.
9780 SmallVector<TemplateSpecCandidate *, 32> Cands;
9781 Cands.reserve(size());
9782 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9783 if (Cand->Specialization)
9784 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009785 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009786 // in general, want to list every possible builtin candidate.
9787 }
9788
9789 std::sort(Cands.begin(), Cands.end(),
9790 CompareTemplateSpecCandidatesForDisplay(S));
9791
9792 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9793 // for generalization purposes (?).
9794 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9795
9796 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9797 unsigned CandsShown = 0;
9798 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9799 TemplateSpecCandidate *Cand = *I;
9800
9801 // Set an arbitrary limit on the number of candidates we'll spam
9802 // the user with. FIXME: This limit should depend on details of the
9803 // candidate list.
9804 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9805 break;
9806 ++CandsShown;
9807
9808 assert(Cand->Specialization &&
9809 "Non-matching built-in candidates are not added to Cands.");
9810 Cand->NoteDeductionFailure(S);
9811 }
9812
9813 if (I != E)
9814 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9815}
9816
Douglas Gregorb491ed32011-02-19 21:32:49 +00009817// [PossiblyAFunctionType] --> [Return]
9818// NonFunctionType --> NonFunctionType
9819// R (A) --> R(A)
9820// R (*)(A) --> R (A)
9821// R (&)(A) --> R (A)
9822// R (S::*)(A) --> R (A)
9823QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9824 QualType Ret = PossiblyAFunctionType;
9825 if (const PointerType *ToTypePtr =
9826 PossiblyAFunctionType->getAs<PointerType>())
9827 Ret = ToTypePtr->getPointeeType();
9828 else if (const ReferenceType *ToTypeRef =
9829 PossiblyAFunctionType->getAs<ReferenceType>())
9830 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009831 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009832 PossiblyAFunctionType->getAs<MemberPointerType>())
9833 Ret = MemTypePtr->getPointeeType();
9834 Ret =
9835 Context.getCanonicalType(Ret).getUnqualifiedType();
9836 return Ret;
9837}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009838
Richard Smith17c00b42014-11-12 01:24:00 +00009839namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009840// A helper class to help with address of function resolution
9841// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +00009842class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009843 Sema& S;
9844 Expr* SourceExpr;
9845 const QualType& TargetType;
9846 QualType TargetFunctionType; // Extracted function type from target type
9847
9848 bool Complain;
9849 //DeclAccessPair& ResultFunctionAccessPair;
9850 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009851
Douglas Gregorb491ed32011-02-19 21:32:49 +00009852 bool TargetTypeIsNonStaticMemberFunction;
9853 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009854 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009855
Douglas Gregorb491ed32011-02-19 21:32:49 +00009856 OverloadExpr::FindResult OvlExprInfo;
9857 OverloadExpr *OvlExpr;
9858 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009859 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009860 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009861
Douglas Gregorb491ed32011-02-19 21:32:49 +00009862public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009863 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9864 const QualType &TargetType, bool Complain)
9865 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9866 Complain(Complain), Context(S.getASTContext()),
9867 TargetTypeIsNonStaticMemberFunction(
9868 !!TargetType->getAs<MemberPointerType>()),
9869 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009870 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009871 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9872 OvlExpr(OvlExprInfo.Expression),
9873 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009874 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009875
David Majnemera4f7c7a2013-08-01 06:13:59 +00009876 if (TargetFunctionType->isFunctionType()) {
9877 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9878 if (!UME->isImplicitAccess() &&
9879 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9880 StaticMemberFunctionFromBoundPointer = true;
9881 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9882 DeclAccessPair dap;
9883 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9884 OvlExpr, false, &dap)) {
9885 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9886 if (!Method->isStatic()) {
9887 // If the target type is a non-function type and the function found
9888 // is a non-static member function, pretend as if that was the
9889 // target, it's the only possible type to end up with.
9890 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009891
David Majnemera4f7c7a2013-08-01 06:13:59 +00009892 // And skip adding the function if its not in the proper form.
9893 // We'll diagnose this due to an empty set of functions.
9894 if (!OvlExprInfo.HasFormOfMemberPointer)
9895 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009896 }
9897
David Majnemera4f7c7a2013-08-01 06:13:59 +00009898 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009899 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009900 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009901 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009902
9903 if (OvlExpr->hasExplicitTemplateArgs())
9904 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009905
Douglas Gregorb491ed32011-02-19 21:32:49 +00009906 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9907 // C++ [over.over]p4:
9908 // If more than one function is selected, [...]
9909 if (Matches.size() > 1) {
9910 if (FoundNonTemplateFunction)
9911 EliminateAllTemplateMatches();
9912 else
9913 EliminateAllExceptMostSpecializedTemplate();
9914 }
9915 }
9916 }
9917
9918private:
9919 bool isTargetTypeAFunction() const {
9920 return TargetFunctionType->isFunctionType();
9921 }
9922
9923 // [ToType] [Return]
9924
9925 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9926 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9927 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9928 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9929 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9930 }
9931
9932 // return true if any matching specializations were found
9933 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9934 const DeclAccessPair& CurAccessFunPair) {
9935 if (CXXMethodDecl *Method
9936 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9937 // Skip non-static function templates when converting to pointer, and
9938 // static when converting to member pointer.
9939 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9940 return false;
9941 }
9942 else if (TargetTypeIsNonStaticMemberFunction)
9943 return false;
9944
9945 // C++ [over.over]p2:
9946 // If the name is a function template, template argument deduction is
9947 // done (14.8.2.2), and if the argument deduction succeeds, the
9948 // resulting template argument list is used to generate a single
9949 // function template specialization, which is added to the set of
9950 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +00009951 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009952 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009953 if (Sema::TemplateDeductionResult Result
9954 = S.DeduceTemplateArguments(FunctionTemplate,
9955 &OvlExplicitTemplateArgs,
9956 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009957 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009958 // Make a note of the failed deduction for diagnostics.
9959 FailedCandidates.addCandidate()
9960 .set(FunctionTemplate->getTemplatedDecl(),
9961 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009962 return false;
9963 }
9964
Douglas Gregor19a41f12013-04-17 08:45:07 +00009965 // Template argument deduction ensures that we have an exact match or
9966 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009967 // This function template specicalization works.
9968 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009969 assert(S.isSameOrCompatibleFunctionType(
9970 Context.getCanonicalType(Specialization->getType()),
9971 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009972 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9973 return true;
9974 }
9975
9976 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9977 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009978 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009979 // Skip non-static functions when converting to pointer, and static
9980 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009981 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9982 return false;
9983 }
9984 else if (TargetTypeIsNonStaticMemberFunction)
9985 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009986
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009987 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009988 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009989 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009990 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009991 return false;
9992
Richard Smith2a7d4812013-05-04 07:00:32 +00009993 // If any candidate has a placeholder return type, trigger its deduction
9994 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00009995 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +00009996 FunDecl->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00009997 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9998 return false;
9999
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000010000 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010001 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10002 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +000010003 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
10004 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010005 Matches.push_back(std::make_pair(CurAccessFunPair,
10006 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010007 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010008 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010009 }
Mike Stump11289f42009-09-09 15:08:12 +000010010 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010011
10012 return false;
10013 }
10014
10015 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10016 bool Ret = false;
10017
10018 // If the overload expression doesn't have the form of a pointer to
10019 // member, don't try to convert it to a pointer-to-member type.
10020 if (IsInvalidFormOfPointerToMemberFunction())
10021 return false;
10022
10023 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10024 E = OvlExpr->decls_end();
10025 I != E; ++I) {
10026 // Look through any using declarations to find the underlying function.
10027 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10028
10029 // C++ [over.over]p3:
10030 // Non-member functions and static member functions match
10031 // targets of type "pointer-to-function" or "reference-to-function."
10032 // Nonstatic member functions match targets of
10033 // type "pointer-to-member-function."
10034 // Note that according to DR 247, the containing class does not matter.
10035 if (FunctionTemplateDecl *FunctionTemplate
10036 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10037 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10038 Ret = true;
10039 }
10040 // If we have explicit template arguments supplied, skip non-templates.
10041 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10042 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10043 Ret = true;
10044 }
10045 assert(Ret || Matches.empty());
10046 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010047 }
10048
Douglas Gregorb491ed32011-02-19 21:32:49 +000010049 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010050 // [...] and any given function template specialization F1 is
10051 // eliminated if the set contains a second function template
10052 // specialization whose function template is more specialized
10053 // than the function template of F1 according to the partial
10054 // ordering rules of 14.5.5.2.
10055
10056 // The algorithm specified above is quadratic. We instead use a
10057 // two-pass algorithm (similar to the one used to identify the
10058 // best viable function in an overload set) that identifies the
10059 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010060
10061 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10062 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10063 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010064
Larisse Voufo98b20f12013-07-19 23:00:19 +000010065 // TODO: It looks like FailedCandidates does not serve much purpose
10066 // here, since the no_viable diagnostic has index 0.
10067 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010068 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010069 SourceExpr->getLocStart(), S.PDiag(),
10070 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10071 .second->getDeclName(),
10072 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10073 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010074
Douglas Gregorb491ed32011-02-19 21:32:49 +000010075 if (Result != MatchesCopy.end()) {
10076 // Make it the first and only element
10077 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10078 Matches[0].second = cast<FunctionDecl>(*Result);
10079 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +000010080 }
10081 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010082
Douglas Gregorb491ed32011-02-19 21:32:49 +000010083 void EliminateAllTemplateMatches() {
10084 // [...] any function template specializations in the set are
10085 // eliminated if the set also contains a non-template function, [...]
10086 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010087 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010088 ++I;
10089 else {
10090 Matches[I] = Matches[--N];
10091 Matches.set_size(N);
10092 }
10093 }
10094 }
10095
10096public:
10097 void ComplainNoMatchesFound() const {
10098 assert(Matches.empty());
10099 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10100 << OvlExpr->getName() << TargetFunctionType
10101 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010102 if (FailedCandidates.empty())
10103 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10104 else {
10105 // We have some deduction failure messages. Use them to diagnose
10106 // the function templates, and diagnose the non-template candidates
10107 // normally.
10108 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10109 IEnd = OvlExpr->decls_end();
10110 I != IEnd; ++I)
10111 if (FunctionDecl *Fun =
10112 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10113 S.NoteOverloadCandidate(Fun, TargetFunctionType);
10114 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10115 }
10116 }
10117
Douglas Gregorb491ed32011-02-19 21:32:49 +000010118 bool IsInvalidFormOfPointerToMemberFunction() const {
10119 return TargetTypeIsNonStaticMemberFunction &&
10120 !OvlExprInfo.HasFormOfMemberPointer;
10121 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010122
Douglas Gregorb491ed32011-02-19 21:32:49 +000010123 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10124 // TODO: Should we condition this on whether any functions might
10125 // have matched, or is it more appropriate to do that in callers?
10126 // TODO: a fixit wouldn't hurt.
10127 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10128 << TargetType << OvlExpr->getSourceRange();
10129 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010130
10131 bool IsStaticMemberFunctionFromBoundPointer() const {
10132 return StaticMemberFunctionFromBoundPointer;
10133 }
10134
10135 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10136 S.Diag(OvlExpr->getLocStart(),
10137 diag::err_invalid_form_pointer_member_function)
10138 << OvlExpr->getSourceRange();
10139 }
10140
Douglas Gregorb491ed32011-02-19 21:32:49 +000010141 void ComplainOfInvalidConversion() const {
10142 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10143 << OvlExpr->getName() << TargetType;
10144 }
10145
10146 void ComplainMultipleMatchesFound() const {
10147 assert(Matches.size() > 1);
10148 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10149 << OvlExpr->getName()
10150 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +000010151 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010152 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010153
10154 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10155
Douglas Gregorb491ed32011-02-19 21:32:49 +000010156 int getNumMatches() const { return Matches.size(); }
10157
10158 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010159 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010160 return Matches[0].second;
10161 }
10162
10163 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010164 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010165 return &Matches[0].first;
10166 }
10167};
Richard Smith17c00b42014-11-12 01:24:00 +000010168}
10169
Douglas Gregorb491ed32011-02-19 21:32:49 +000010170/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10171/// an overloaded function (C++ [over.over]), where @p From is an
10172/// expression with overloaded function type and @p ToType is the type
10173/// we're trying to resolve to. For example:
10174///
10175/// @code
10176/// int f(double);
10177/// int f(int);
10178///
10179/// int (*pfd)(double) = f; // selects f(double)
10180/// @endcode
10181///
10182/// This routine returns the resulting FunctionDecl if it could be
10183/// resolved, and NULL otherwise. When @p Complain is true, this
10184/// routine will emit diagnostics if there is an error.
10185FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010186Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10187 QualType TargetType,
10188 bool Complain,
10189 DeclAccessPair &FoundResult,
10190 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010191 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010192
10193 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10194 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010195 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010196 FunctionDecl *Fn = nullptr;
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010197 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010198 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10199 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10200 else
10201 Resolver.ComplainNoMatchesFound();
10202 }
10203 else if (NumMatches > 1 && Complain)
10204 Resolver.ComplainMultipleMatchesFound();
10205 else if (NumMatches == 1) {
10206 Fn = Resolver.getMatchingFunctionDecl();
10207 assert(Fn);
10208 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010209 if (Complain) {
10210 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10211 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10212 else
10213 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10214 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010215 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010216
10217 if (pHadMultipleCandidates)
10218 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010219 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010220}
10221
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010222/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010223/// resolve that overloaded function expression down to a single function.
10224///
10225/// This routine can only resolve template-ids that refer to a single function
10226/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010227/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010228/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010229///
10230/// If no template-ids are found, no diagnostics are emitted and NULL is
10231/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010232FunctionDecl *
10233Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10234 bool Complain,
10235 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010236 // C++ [over.over]p1:
10237 // [...] [Note: any redundant set of parentheses surrounding the
10238 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010239 // C++ [over.over]p1:
10240 // [...] The overloaded function name can be preceded by the &
10241 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010242
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010243 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010244 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010245 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010246
10247 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010248 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010249 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010250
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010251 // Look through all of the overloaded functions, searching for one
10252 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010253 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010254 for (UnresolvedSetIterator I = ovl->decls_begin(),
10255 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010256 // C++0x [temp.arg.explicit]p3:
10257 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010258 // where deduction is not done, if a template argument list is
10259 // specified and it, along with any default template arguments,
10260 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010261 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010262 FunctionTemplateDecl *FunctionTemplate
10263 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010264
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010265 // C++ [over.over]p2:
10266 // If the name is a function template, template argument deduction is
10267 // done (14.8.2.2), and if the argument deduction succeeds, the
10268 // resulting template argument list is used to generate a single
10269 // function template specialization, which is added to the set of
10270 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010271 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010272 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010273 if (TemplateDeductionResult Result
10274 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010275 Specialization, Info,
10276 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010277 // Make a note of the failed deduction for diagnostics.
10278 // TODO: Actually use the failed-deduction info?
10279 FailedCandidates.addCandidate()
10280 .set(FunctionTemplate->getTemplatedDecl(),
10281 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010282 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010283 }
10284
John McCall0009fcc2011-04-26 20:42:42 +000010285 assert(Specialization && "no specialization and no error?");
10286
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010287 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010288 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010289 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010290 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10291 << ovl->getName();
10292 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010293 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010294 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010295 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010296
John McCall0009fcc2011-04-26 20:42:42 +000010297 Matched = Specialization;
10298 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010299 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010300
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010301 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010302 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010303 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010304 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010305
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010306 return Matched;
10307}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010308
Douglas Gregor1beec452011-03-12 01:48:56 +000010309
10310
10311
John McCall50a2c2c2011-10-11 23:14:30 +000010312// Resolve and fix an overloaded expression that can be resolved
10313// because it identifies a single function template specialization.
10314//
Douglas Gregor1beec452011-03-12 01:48:56 +000010315// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010316//
10317// Return true if it was logically possible to so resolve the
10318// expression, regardless of whether or not it succeeded. Always
10319// returns true if 'complain' is set.
10320bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10321 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10322 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010323 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010324 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010325 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010326
John McCall50a2c2c2011-10-11 23:14:30 +000010327 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010328
John McCall0009fcc2011-04-26 20:42:42 +000010329 DeclAccessPair found;
10330 ExprResult SingleFunctionExpression;
10331 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10332 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010333 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010334 SrcExpr = ExprError();
10335 return true;
10336 }
John McCall0009fcc2011-04-26 20:42:42 +000010337
10338 // It is only correct to resolve to an instance method if we're
10339 // resolving a form that's permitted to be a pointer to member.
10340 // Otherwise we'll end up making a bound member expression, which
10341 // is illegal in all the contexts we resolve like this.
10342 if (!ovl.HasFormOfMemberPointer &&
10343 isa<CXXMethodDecl>(fn) &&
10344 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010345 if (!complain) return false;
10346
10347 Diag(ovl.Expression->getExprLoc(),
10348 diag::err_bound_member_function)
10349 << 0 << ovl.Expression->getSourceRange();
10350
10351 // TODO: I believe we only end up here if there's a mix of
10352 // static and non-static candidates (otherwise the expression
10353 // would have 'bound member' type, not 'overload' type).
10354 // Ideally we would note which candidate was chosen and why
10355 // the static candidates were rejected.
10356 SrcExpr = ExprError();
10357 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010358 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010359
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010360 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010361 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010362 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010363
10364 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010365 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010366 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010367 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010368 if (SingleFunctionExpression.isInvalid()) {
10369 SrcExpr = ExprError();
10370 return true;
10371 }
10372 }
John McCall0009fcc2011-04-26 20:42:42 +000010373 }
10374
10375 if (!SingleFunctionExpression.isUsable()) {
10376 if (complain) {
10377 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10378 << ovl.Expression->getName()
10379 << DestTypeForComplaining
10380 << OpRangeForComplaining
10381 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010382 NoteAllOverloadCandidates(SrcExpr.get());
10383
10384 SrcExpr = ExprError();
10385 return true;
10386 }
10387
10388 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010389 }
10390
John McCall50a2c2c2011-10-11 23:14:30 +000010391 SrcExpr = SingleFunctionExpression;
10392 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010393}
10394
Douglas Gregorcabea402009-09-22 15:41:20 +000010395/// \brief Add a single candidate to the overload set.
10396static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010397 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010398 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010399 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010400 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010401 bool PartialOverloading,
10402 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010403 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010404 if (isa<UsingShadowDecl>(Callee))
10405 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10406
Douglas Gregorcabea402009-09-22 15:41:20 +000010407 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010408 if (ExplicitTemplateArgs) {
10409 assert(!KnownValid && "Explicit template arguments?");
10410 return;
10411 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010412 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10413 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010414 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010415 return;
John McCalld14a8642009-11-21 08:51:07 +000010416 }
10417
10418 if (FunctionTemplateDecl *FuncTemplate
10419 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010420 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010421 ExplicitTemplateArgs, Args, CandidateSet,
10422 /*SuppressUsedConversions=*/false,
10423 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010424 return;
10425 }
10426
Richard Smith95ce4f62011-06-26 22:19:54 +000010427 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010428}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010429
Douglas Gregorcabea402009-09-22 15:41:20 +000010430/// \brief Add the overload candidates named by callee and/or found by argument
10431/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010432void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010433 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010434 OverloadCandidateSet &CandidateSet,
10435 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010436
10437#ifndef NDEBUG
10438 // Verify that ArgumentDependentLookup is consistent with the rules
10439 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010440 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010441 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10442 // and let Y be the lookup set produced by argument dependent
10443 // lookup (defined as follows). If X contains
10444 //
10445 // -- a declaration of a class member, or
10446 //
10447 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010448 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010449 //
10450 // -- a declaration that is neither a function or a function
10451 // template
10452 //
10453 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010454
John McCall57500772009-12-16 12:17:52 +000010455 if (ULE->requiresADL()) {
10456 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10457 E = ULE->decls_end(); I != E; ++I) {
10458 assert(!(*I)->getDeclContext()->isRecord());
10459 assert(isa<UsingShadowDecl>(*I) ||
10460 !(*I)->getDeclContext()->isFunctionOrMethod());
10461 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010462 }
10463 }
10464#endif
10465
John McCall57500772009-12-16 12:17:52 +000010466 // It would be nice to avoid this copy.
10467 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010468 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010469 if (ULE->hasExplicitTemplateArgs()) {
10470 ULE->copyTemplateArgumentsInto(TABuffer);
10471 ExplicitTemplateArgs = &TABuffer;
10472 }
10473
10474 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10475 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010476 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10477 CandidateSet, PartialOverloading,
10478 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010479
John McCall57500772009-12-16 12:17:52 +000010480 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010481 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010482 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010483 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010484}
John McCalld681c392009-12-16 08:11:27 +000010485
Richard Smith0603bbb2013-06-12 22:56:54 +000010486/// Determine whether a declaration with the specified name could be moved into
10487/// a different namespace.
10488static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10489 switch (Name.getCXXOverloadedOperator()) {
10490 case OO_New: case OO_Array_New:
10491 case OO_Delete: case OO_Array_Delete:
10492 return false;
10493
10494 default:
10495 return true;
10496 }
10497}
10498
Richard Smith998a5912011-06-05 22:42:48 +000010499/// Attempt to recover from an ill-formed use of a non-dependent name in a
10500/// template, where the non-dependent name was declared after the template
10501/// was defined. This is common in code written for a compilers which do not
10502/// correctly implement two-stage name lookup.
10503///
10504/// Returns true if a viable candidate was found and a diagnostic was issued.
10505static bool
10506DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10507 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010508 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010509 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010510 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010511 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10512 return false;
10513
10514 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010515 if (DC->isTransparentContext())
10516 continue;
10517
Richard Smith998a5912011-06-05 22:42:48 +000010518 SemaRef.LookupQualifiedName(R, DC);
10519
10520 if (!R.empty()) {
10521 R.suppressDiagnostics();
10522
10523 if (isa<CXXRecordDecl>(DC)) {
10524 // Don't diagnose names we find in classes; we get much better
10525 // diagnostics for these from DiagnoseEmptyLookup.
10526 R.clear();
10527 return false;
10528 }
10529
Richard Smith100b24a2014-04-17 01:52:14 +000010530 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010531 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10532 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010533 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010534 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010535
10536 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010537 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010538 // No viable functions. Don't bother the user with notes for functions
10539 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010540 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010541 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010542 }
Richard Smith998a5912011-06-05 22:42:48 +000010543
10544 // Find the namespaces where ADL would have looked, and suggest
10545 // declaring the function there instead.
10546 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10547 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010548 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010549 AssociatedNamespaces,
10550 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010551 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010552 if (canBeDeclaredInNamespace(R.getLookupName())) {
10553 DeclContext *Std = SemaRef.getStdNamespace();
10554 for (Sema::AssociatedNamespaceSet::iterator
10555 it = AssociatedNamespaces.begin(),
10556 end = AssociatedNamespaces.end(); it != end; ++it) {
10557 // Never suggest declaring a function within namespace 'std'.
10558 if (Std && Std->Encloses(*it))
10559 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010560
Richard Smith0603bbb2013-06-12 22:56:54 +000010561 // Never suggest declaring a function within a namespace with a
10562 // reserved name, like __gnu_cxx.
10563 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10564 if (NS &&
10565 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10566 continue;
10567
10568 SuggestedNamespaces.insert(*it);
10569 }
Richard Smith998a5912011-06-05 22:42:48 +000010570 }
10571
10572 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10573 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010574 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010575 SemaRef.Diag(Best->Function->getLocation(),
10576 diag::note_not_found_by_two_phase_lookup)
10577 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010578 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010579 SemaRef.Diag(Best->Function->getLocation(),
10580 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010581 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010582 } else {
10583 // FIXME: It would be useful to list the associated namespaces here,
10584 // but the diagnostics infrastructure doesn't provide a way to produce
10585 // a localized representation of a list of items.
10586 SemaRef.Diag(Best->Function->getLocation(),
10587 diag::note_not_found_by_two_phase_lookup)
10588 << R.getLookupName() << 2;
10589 }
10590
10591 // Try to recover by calling this function.
10592 return true;
10593 }
10594
10595 R.clear();
10596 }
10597
10598 return false;
10599}
10600
10601/// Attempt to recover from ill-formed use of a non-dependent operator in a
10602/// template, where the non-dependent operator was declared after the template
10603/// was defined.
10604///
10605/// Returns true if a viable candidate was found and a diagnostic was issued.
10606static bool
10607DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10608 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010609 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010610 DeclarationName OpName =
10611 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10612 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10613 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010614 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010615 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010616}
10617
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010618namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010619class BuildRecoveryCallExprRAII {
10620 Sema &SemaRef;
10621public:
10622 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10623 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10624 SemaRef.IsBuildingRecoveryCallExpr = true;
10625 }
10626
10627 ~BuildRecoveryCallExprRAII() {
10628 SemaRef.IsBuildingRecoveryCallExpr = false;
10629 }
10630};
10631
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010632}
10633
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010634static std::unique_ptr<CorrectionCandidateCallback>
10635MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10636 bool HasTemplateArgs, bool AllowTypoCorrection) {
10637 if (!AllowTypoCorrection)
10638 return llvm::make_unique<NoTypoCorrectionCCC>();
10639 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10640 HasTemplateArgs, ME);
10641}
10642
John McCalld681c392009-12-16 08:11:27 +000010643/// Attempts to recover from a call where no functions were found.
10644///
10645/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010646static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010647BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010648 UnresolvedLookupExpr *ULE,
10649 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010650 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010651 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010652 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010653 // Do not try to recover if it is already building a recovery call.
10654 // This stops infinite loops for template instantiations like
10655 //
10656 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10657 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10658 //
10659 if (SemaRef.IsBuildingRecoveryCallExpr)
10660 return ExprError();
10661 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010662
10663 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010664 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010665 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010666
John McCall57500772009-12-16 12:17:52 +000010667 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010668 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010669 if (ULE->hasExplicitTemplateArgs()) {
10670 ULE->copyTemplateArgumentsInto(TABuffer);
10671 ExplicitTemplateArgs = &TABuffer;
10672 }
10673
John McCalld681c392009-12-16 08:11:27 +000010674 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10675 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +000010676 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000010677 OverloadCandidateSet::CSK_Normal,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010678 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +000010679 (!EmptyLookup ||
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010680 SemaRef.DiagnoseEmptyLookup(
10681 S, SS, R,
10682 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10683 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10684 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010685 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010686
John McCall57500772009-12-16 12:17:52 +000010687 assert(!R.empty() && "lookup results empty despite recovery");
10688
10689 // Build an implicit member call if appropriate. Just drop the
10690 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010691 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010692 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010693 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10694 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010695 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010696 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010697 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010698 else
10699 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10700
10701 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010702 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010703
10704 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010705 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010706 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010707 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010708 MultiExprArg(Args.data(), Args.size()),
10709 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010710}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010711
Sam Panzer0f384432012-08-21 00:52:01 +000010712/// \brief Constructs and populates an OverloadedCandidateSet from
10713/// the given function.
10714/// \returns true when an the ExprResult output parameter has been set.
10715bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10716 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010717 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010718 SourceLocation RParenLoc,
10719 OverloadCandidateSet *CandidateSet,
10720 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010721#ifndef NDEBUG
10722 if (ULE->requiresADL()) {
10723 // To do ADL, we must have found an unqualified name.
10724 assert(!ULE->getQualifier() && "qualified name with ADL");
10725
10726 // We don't perform ADL for implicit declarations of builtins.
10727 // Verify that this was correctly set up.
10728 FunctionDecl *F;
10729 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10730 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10731 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010732 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010733
John McCall57500772009-12-16 12:17:52 +000010734 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010735 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010736 }
John McCall57500772009-12-16 12:17:52 +000010737#endif
10738
John McCall4124c492011-10-17 18:40:02 +000010739 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010740 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010741 *Result = ExprError();
10742 return true;
10743 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010744
John McCall57500772009-12-16 12:17:52 +000010745 // Add the functions denoted by the callee to the set of candidate
10746 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010747 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010748
10749 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +000010750 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10751 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +000010752 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010753 // In Microsoft mode, if we are inside a template class member function then
10754 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +000010755 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010756 // classes.
Alp Tokerbfa39342014-01-14 12:51:41 +000010757 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +000010758 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010759 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010760 Context.DependentTy, VK_RValue,
10761 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010762 CE->setTypeDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010763 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000010764 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010765 }
Sam Panzer0f384432012-08-21 00:52:01 +000010766 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +000010767 }
John McCalld681c392009-12-16 08:11:27 +000010768
John McCall4124c492011-10-17 18:40:02 +000010769 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010770 return false;
10771}
John McCall4124c492011-10-17 18:40:02 +000010772
Sam Panzer0f384432012-08-21 00:52:01 +000010773/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10774/// the completed call expression. If overload resolution fails, emits
10775/// diagnostics and returns ExprError()
10776static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10777 UnresolvedLookupExpr *ULE,
10778 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010779 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010780 SourceLocation RParenLoc,
10781 Expr *ExecConfig,
10782 OverloadCandidateSet *CandidateSet,
10783 OverloadCandidateSet::iterator *Best,
10784 OverloadingResult OverloadResult,
10785 bool AllowTypoCorrection) {
10786 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010787 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010788 RParenLoc, /*EmptyLookup=*/true,
10789 AllowTypoCorrection);
10790
10791 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010792 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010793 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010794 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010795 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10796 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010797 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010798 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10799 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010800 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010801
Richard Smith998a5912011-06-05 22:42:48 +000010802 case OR_No_Viable_Function: {
10803 // Try to recover by looking for viable functions which the user might
10804 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010805 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010806 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010807 /*EmptyLookup=*/false,
10808 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010809 if (!Recovery.isInvalid())
10810 return Recovery;
10811
Sam Panzer0f384432012-08-21 00:52:01 +000010812 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010813 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010814 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010815 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010816 break;
Richard Smith998a5912011-06-05 22:42:48 +000010817 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010818
10819 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010820 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010821 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010822 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010823 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010824
Sam Panzer0f384432012-08-21 00:52:01 +000010825 case OR_Deleted: {
10826 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10827 << (*Best)->Function->isDeleted()
10828 << ULE->getName()
10829 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10830 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010831 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010832
Sam Panzer0f384432012-08-21 00:52:01 +000010833 // We emitted an error for the unvailable/deleted function call but keep
10834 // the call in the AST.
10835 FunctionDecl *FDecl = (*Best)->Function;
10836 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010837 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10838 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010839 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010840 }
10841
Douglas Gregorb412e172010-07-25 18:17:45 +000010842 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010843 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010844}
10845
Sam Panzer0f384432012-08-21 00:52:01 +000010846/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10847/// (which eventually refers to the declaration Func) and the call
10848/// arguments Args/NumArgs, attempt to resolve the function call down
10849/// to a specific function. If overload resolution succeeds, returns
10850/// the call expression produced by overload resolution.
10851/// Otherwise, emits diagnostics and returns ExprError.
10852ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10853 UnresolvedLookupExpr *ULE,
10854 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010855 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010856 SourceLocation RParenLoc,
10857 Expr *ExecConfig,
10858 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000010859 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10860 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000010861 ExprResult result;
10862
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010863 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10864 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010865 return result;
10866
10867 OverloadCandidateSet::iterator Best;
10868 OverloadingResult OverloadResult =
10869 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10870
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010871 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010872 RParenLoc, ExecConfig, &CandidateSet,
10873 &Best, OverloadResult,
10874 AllowTypoCorrection);
10875}
10876
John McCall4c4c1df2010-01-26 03:27:55 +000010877static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010878 return Functions.size() > 1 ||
10879 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10880}
10881
Douglas Gregor084d8552009-03-13 23:49:33 +000010882/// \brief Create a unary operation that may resolve to an overloaded
10883/// operator.
10884///
10885/// \param OpLoc The location of the operator itself (e.g., '*').
10886///
10887/// \param OpcIn The UnaryOperator::Opcode that describes this
10888/// operator.
10889///
James Dennett18348b62012-06-22 08:52:37 +000010890/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010891/// considered by overload resolution. The caller needs to build this
10892/// set based on the context using, e.g.,
10893/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10894/// set should not contain any member functions; those will be added
10895/// by CreateOverloadedUnaryOp().
10896///
James Dennett91738ff2012-06-22 10:32:46 +000010897/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010898ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010899Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10900 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010901 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010902 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010903
10904 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10905 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10906 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010907 // TODO: provide better source location info.
10908 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010909
John McCall4124c492011-10-17 18:40:02 +000010910 if (checkPlaceholderForOverload(*this, Input))
10911 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010912
Craig Topperc3ec1492014-05-26 06:22:03 +000010913 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000010914 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010915
Douglas Gregor084d8552009-03-13 23:49:33 +000010916 // For post-increment and post-decrement, add the implicit '0' as
10917 // the second argument, so that we know this is a post-increment or
10918 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010919 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010920 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010921 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10922 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010923 NumArgs = 2;
10924 }
10925
Richard Smithe54c3072013-05-05 15:51:06 +000010926 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10927
Douglas Gregor084d8552009-03-13 23:49:33 +000010928 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010929 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010930 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10931 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010932
Craig Topperc3ec1492014-05-26 06:22:03 +000010933 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010934 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010935 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010936 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010937 /*ADL*/ true, IsOverloaded(Fns),
10938 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010939 return new (Context)
10940 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10941 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010942 }
10943
10944 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000010945 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000010946
10947 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010948 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010949
10950 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010951 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010952
John McCall4c4c1df2010-01-26 03:27:55 +000010953 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000010954 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000010955 /*ExplicitTemplateArgs*/nullptr,
10956 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000010957
Douglas Gregor084d8552009-03-13 23:49:33 +000010958 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010959 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010960
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010961 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10962
Douglas Gregor084d8552009-03-13 23:49:33 +000010963 // Perform overload resolution.
10964 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010965 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010966 case OR_Success: {
10967 // We found a built-in operator or an overloaded operator.
10968 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010969
Douglas Gregor084d8552009-03-13 23:49:33 +000010970 if (FnDecl) {
10971 // We matched an overloaded operator. Build a call to that
10972 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010973
Douglas Gregor084d8552009-03-13 23:49:33 +000010974 // Convert the arguments.
10975 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010976 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010977
John Wiegley01296292011-04-08 18:41:53 +000010978 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000010979 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000010980 Best->FoundDecl, Method);
10981 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010982 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010983 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010984 } else {
10985 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010986 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010987 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010988 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010989 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010990 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010991 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010992 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010993 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010994 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010995 }
10996
Douglas Gregor084d8552009-03-13 23:49:33 +000010997 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000010998 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010999 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011000 if (FnExpr.isInvalid())
11001 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011002
Richard Smithc1564702013-11-15 02:58:23 +000011003 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011004 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011005 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11006 ResultTy = ResultTy.getNonLValueExprType(Context);
11007
Eli Friedman030eee42009-11-18 03:58:17 +000011008 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011009 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011010 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011011 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011012
Alp Toker314cc812014-01-25 16:55:45 +000011013 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011014 return ExprError();
11015
John McCallb268a282010-08-23 23:25:46 +000011016 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011017 } else {
11018 // We matched a built-in operator. Convert the arguments, then
11019 // break out so that we will build the appropriate built-in
11020 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011021 ExprResult InputRes =
11022 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11023 Best->Conversions[0], AA_Passing);
11024 if (InputRes.isInvalid())
11025 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011026 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011027 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011028 }
John Wiegley01296292011-04-08 18:41:53 +000011029 }
11030
11031 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011032 // This is an erroneous use of an operator which can be overloaded by
11033 // a non-member function. Check for non-member operators which were
11034 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011035 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011036 // FIXME: Recover by calling the found function.
11037 return ExprError();
11038
John Wiegley01296292011-04-08 18:41:53 +000011039 // No viable function; fall through to handling this as a
11040 // built-in operator, which will produce an error message for us.
11041 break;
11042
11043 case OR_Ambiguous:
11044 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11045 << UnaryOperator::getOpcodeStr(Opc)
11046 << Input->getType()
11047 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011048 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011049 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11050 return ExprError();
11051
11052 case OR_Deleted:
11053 Diag(OpLoc, diag::err_ovl_deleted_oper)
11054 << Best->Function->isDeleted()
11055 << UnaryOperator::getOpcodeStr(Opc)
11056 << getDeletedOrUnavailableSuffix(Best->Function)
11057 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011058 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011059 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011060 return ExprError();
11061 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011062
11063 // Either we found no viable overloaded operator or we matched a
11064 // built-in operator. In either case, fall through to trying to
11065 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011066 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011067}
11068
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011069/// \brief Create a binary operation that may resolve to an overloaded
11070/// operator.
11071///
11072/// \param OpLoc The location of the operator itself (e.g., '+').
11073///
11074/// \param OpcIn The BinaryOperator::Opcode that describes this
11075/// operator.
11076///
James Dennett18348b62012-06-22 08:52:37 +000011077/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011078/// considered by overload resolution. The caller needs to build this
11079/// set based on the context using, e.g.,
11080/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11081/// set should not contain any member functions; those will be added
11082/// by CreateOverloadedBinOp().
11083///
11084/// \param LHS Left-hand argument.
11085/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011086ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011087Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000011088 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000011089 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011090 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011091 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011092 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011093
11094 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11095 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11096 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11097
11098 // If either side is type-dependent, create an appropriate dependent
11099 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011100 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011101 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011102 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011103 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011104 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011105 return new (Context) BinaryOperator(
11106 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11107 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011108
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011109 return new (Context) CompoundAssignOperator(
11110 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11111 Context.DependentTy, Context.DependentTy, OpLoc,
11112 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011113 }
John McCall4c4c1df2010-01-26 03:27:55 +000011114
11115 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011116 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011117 // TODO: provide better source location info in DNLoc component.
11118 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011119 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011120 = UnresolvedLookupExpr::Create(Context, NamingClass,
11121 NestedNameSpecifierLoc(), OpNameInfo,
11122 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011123 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011124 return new (Context)
11125 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11126 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011127 }
11128
John McCall4124c492011-10-17 18:40:02 +000011129 // Always do placeholder-like conversions on the RHS.
11130 if (checkPlaceholderForOverload(*this, Args[1]))
11131 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011132
John McCall526ab472011-10-25 17:37:35 +000011133 // Do placeholder-like conversion on the LHS; note that we should
11134 // not get here with a PseudoObject LHS.
11135 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011136 if (checkPlaceholderForOverload(*this, Args[0]))
11137 return ExprError();
11138
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011139 // If this is the assignment operator, we only perform overload resolution
11140 // if the left-hand side is a class or enumeration type. This is actually
11141 // a hack. The standard requires that we do overload resolution between the
11142 // various built-in candidates, but as DR507 points out, this can lead to
11143 // problems. So we do it this way, which pretty much follows what GCC does.
11144 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011145 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011146 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011147
John McCalle26a8722010-12-04 08:14:53 +000011148 // If this is the .* operator, which is not overloadable, just
11149 // create a built-in binary operator.
11150 if (Opc == BO_PtrMemD)
11151 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11152
Douglas Gregor084d8552009-03-13 23:49:33 +000011153 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011154 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011155
11156 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011157 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011158
11159 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011160 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011161
Richard Smith0daabd72014-09-23 20:31:39 +000011162 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11163 // performed for an assignment operator (nor for operator[] nor operator->,
11164 // which don't get here).
11165 if (Opc != BO_Assign)
11166 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11167 /*ExplicitTemplateArgs*/ nullptr,
11168 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011169
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011170 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011171 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011172
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011173 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11174
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011175 // Perform overload resolution.
11176 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011177 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011178 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011179 // We found a built-in operator or an overloaded operator.
11180 FunctionDecl *FnDecl = Best->Function;
11181
11182 if (FnDecl) {
11183 // We matched an overloaded operator. Build a call to that
11184 // operator.
11185
11186 // Convert the arguments.
11187 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011188 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011189 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011190
Chandler Carruth8e543b32010-12-12 08:17:55 +000011191 ExprResult Arg1 =
11192 PerformCopyInitialization(
11193 InitializedEntity::InitializeParameter(Context,
11194 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011195 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011196 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011197 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011198
John Wiegley01296292011-04-08 18:41:53 +000011199 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011200 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011201 Best->FoundDecl, Method);
11202 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011203 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011204 Args[0] = Arg0.getAs<Expr>();
11205 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011206 } else {
11207 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011208 ExprResult Arg0 = PerformCopyInitialization(
11209 InitializedEntity::InitializeParameter(Context,
11210 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011211 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011212 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011213 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011214
Chandler Carruth8e543b32010-12-12 08:17:55 +000011215 ExprResult Arg1 =
11216 PerformCopyInitialization(
11217 InitializedEntity::InitializeParameter(Context,
11218 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011219 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011220 if (Arg1.isInvalid())
11221 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011222 Args[0] = LHS = Arg0.getAs<Expr>();
11223 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011224 }
11225
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011226 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011227 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011228 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011229 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011230 if (FnExpr.isInvalid())
11231 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011232
Richard Smithc1564702013-11-15 02:58:23 +000011233 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011234 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011235 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11236 ResultTy = ResultTy.getNonLValueExprType(Context);
11237
John McCallb268a282010-08-23 23:25:46 +000011238 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011239 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011240 Args, ResultTy, VK, OpLoc,
11241 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011242
Alp Toker314cc812014-01-25 16:55:45 +000011243 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011244 FnDecl))
11245 return ExprError();
11246
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011247 ArrayRef<const Expr *> ArgsArray(Args, 2);
11248 // Cut off the implicit 'this'.
11249 if (isa<CXXMethodDecl>(FnDecl))
11250 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011251
11252 // Check for a self move.
11253 if (Op == OO_Equal)
11254 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11255
11256 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011257 TheCall->getSourceRange(), VariadicDoesNotApply);
11258
John McCallb268a282010-08-23 23:25:46 +000011259 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011260 } else {
11261 // We matched a built-in operator. Convert the arguments, then
11262 // break out so that we will build the appropriate built-in
11263 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011264 ExprResult ArgsRes0 =
11265 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11266 Best->Conversions[0], AA_Passing);
11267 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011268 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011269 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011270
John Wiegley01296292011-04-08 18:41:53 +000011271 ExprResult ArgsRes1 =
11272 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11273 Best->Conversions[1], AA_Passing);
11274 if (ArgsRes1.isInvalid())
11275 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011276 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011277 break;
11278 }
11279 }
11280
Douglas Gregor66950a32009-09-30 21:46:01 +000011281 case OR_No_Viable_Function: {
11282 // C++ [over.match.oper]p9:
11283 // If the operator is the operator , [...] and there are no
11284 // viable functions, then the operator is assumed to be the
11285 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011286 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011287 break;
11288
Chandler Carruth8e543b32010-12-12 08:17:55 +000011289 // For class as left operand for assignment or compound assigment
11290 // operator do not fall through to handling in built-in, but report that
11291 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011292 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011293 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011294 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011295 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11296 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011297 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011298 if (Args[0]->getType()->isIncompleteType()) {
11299 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11300 << Args[0]->getType()
11301 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11302 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011303 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011304 // This is an erroneous use of an operator which can be overloaded by
11305 // a non-member function. Check for non-member operators which were
11306 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011307 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011308 // FIXME: Recover by calling the found function.
11309 return ExprError();
11310
Douglas Gregor66950a32009-09-30 21:46:01 +000011311 // No viable function; try to create a built-in operation, which will
11312 // produce an error. Then, show the non-viable candidates.
11313 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011314 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011315 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011316 "C++ binary operator overloading is missing candidates!");
11317 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011318 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011319 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011320 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011321 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011322
11323 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011324 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011325 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011326 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011327 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011328 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011329 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011330 return ExprError();
11331
11332 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011333 if (isImplicitlyDeleted(Best->Function)) {
11334 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11335 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011336 << Context.getRecordType(Method->getParent())
11337 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011338
Richard Smithde1a4872012-12-28 12:23:24 +000011339 // The user probably meant to call this special member. Just
11340 // explain why it's deleted.
11341 NoteDeletedFunction(Method);
11342 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011343 } else {
11344 Diag(OpLoc, diag::err_ovl_deleted_oper)
11345 << Best->Function->isDeleted()
11346 << BinaryOperator::getOpcodeStr(Opc)
11347 << getDeletedOrUnavailableSuffix(Best->Function)
11348 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11349 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011350 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011351 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011352 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011353 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011354
Douglas Gregor66950a32009-09-30 21:46:01 +000011355 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011356 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011357}
11358
John McCalldadc5752010-08-24 06:29:42 +000011359ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011360Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11361 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011362 Expr *Base, Expr *Idx) {
11363 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011364 DeclarationName OpName =
11365 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11366
11367 // If either side is type-dependent, create an appropriate dependent
11368 // expression.
11369 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11370
Craig Topperc3ec1492014-05-26 06:22:03 +000011371 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011372 // CHECKME: no 'operator' keyword?
11373 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11374 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011375 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011376 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011377 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011378 /*ADL*/ true, /*Overloaded*/ false,
11379 UnresolvedSetIterator(),
11380 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011381 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011382
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011383 return new (Context)
11384 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11385 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011386 }
11387
John McCall4124c492011-10-17 18:40:02 +000011388 // Handle placeholders on both operands.
11389 if (checkPlaceholderForOverload(*this, Args[0]))
11390 return ExprError();
11391 if (checkPlaceholderForOverload(*this, Args[1]))
11392 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011393
Sebastian Redladba46e2009-10-29 20:17:01 +000011394 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011395 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011396
11397 // Subscript can only be overloaded as a member function.
11398
11399 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011400 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011401
11402 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011403 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011404
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011405 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11406
Sebastian Redladba46e2009-10-29 20:17:01 +000011407 // Perform overload resolution.
11408 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011409 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011410 case OR_Success: {
11411 // We found a built-in operator or an overloaded operator.
11412 FunctionDecl *FnDecl = Best->Function;
11413
11414 if (FnDecl) {
11415 // We matched an overloaded operator. Build a call to that
11416 // operator.
11417
John McCalla0296f72010-03-19 07:35:19 +000011418 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011419
Sebastian Redladba46e2009-10-29 20:17:01 +000011420 // Convert the arguments.
11421 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011422 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011423 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011424 Best->FoundDecl, Method);
11425 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011426 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011427 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011428
Anders Carlssona68e51e2010-01-29 18:37:50 +000011429 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011430 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011431 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011432 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011433 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011434 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011435 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011436 if (InputInit.isInvalid())
11437 return ExprError();
11438
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011439 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011440
Sebastian Redladba46e2009-10-29 20:17:01 +000011441 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011442 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11443 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011444 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011445 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011446 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011447 OpLocInfo.getLoc(),
11448 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011449 if (FnExpr.isInvalid())
11450 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011451
Richard Smithc1564702013-11-15 02:58:23 +000011452 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011453 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011454 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11455 ResultTy = ResultTy.getNonLValueExprType(Context);
11456
John McCallb268a282010-08-23 23:25:46 +000011457 CXXOperatorCallExpr *TheCall =
11458 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011459 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011460 ResultTy, VK, RLoc,
11461 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011462
Alp Toker314cc812014-01-25 16:55:45 +000011463 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011464 return ExprError();
11465
John McCallb268a282010-08-23 23:25:46 +000011466 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011467 } else {
11468 // We matched a built-in operator. Convert the arguments, then
11469 // break out so that we will build the appropriate built-in
11470 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011471 ExprResult ArgsRes0 =
11472 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11473 Best->Conversions[0], AA_Passing);
11474 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011475 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011476 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011477
11478 ExprResult ArgsRes1 =
11479 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11480 Best->Conversions[1], AA_Passing);
11481 if (ArgsRes1.isInvalid())
11482 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011483 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011484
11485 break;
11486 }
11487 }
11488
11489 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011490 if (CandidateSet.empty())
11491 Diag(LLoc, diag::err_ovl_no_oper)
11492 << Args[0]->getType() << /*subscript*/ 0
11493 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11494 else
11495 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11496 << Args[0]->getType()
11497 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011498 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011499 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011500 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011501 }
11502
11503 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011504 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011505 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011506 << Args[0]->getType() << Args[1]->getType()
11507 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011508 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011509 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011510 return ExprError();
11511
11512 case OR_Deleted:
11513 Diag(LLoc, diag::err_ovl_deleted_oper)
11514 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011515 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011516 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011517 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011518 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011519 return ExprError();
11520 }
11521
11522 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011523 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011524}
11525
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011526/// BuildCallToMemberFunction - Build a call to a member
11527/// function. MemExpr is the expression that refers to the member
11528/// function (and includes the object parameter), Args/NumArgs are the
11529/// arguments to the function call (not including the object
11530/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011531/// expression refers to a non-static member function or an overloaded
11532/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011533ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011534Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011535 SourceLocation LParenLoc,
11536 MultiExprArg Args,
11537 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011538 assert(MemExprE->getType() == Context.BoundMemberTy ||
11539 MemExprE->getType() == Context.OverloadTy);
11540
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011541 // Dig out the member expression. This holds both the object
11542 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011543 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011544
John McCall0009fcc2011-04-26 20:42:42 +000011545 // Determine whether this is a call to a pointer-to-member function.
11546 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11547 assert(op->getType() == Context.BoundMemberTy);
11548 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11549
11550 QualType fnType =
11551 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11552
11553 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11554 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011555 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011556
11557 // Check that the object type isn't more qualified than the
11558 // member function we're calling.
11559 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11560
11561 QualType objectType = op->getLHS()->getType();
11562 if (op->getOpcode() == BO_PtrMemI)
11563 objectType = objectType->castAs<PointerType>()->getPointeeType();
11564 Qualifiers objectQuals = objectType.getQualifiers();
11565
11566 Qualifiers difference = objectQuals - funcQuals;
11567 difference.removeObjCGCAttr();
11568 difference.removeAddressSpace();
11569 if (difference) {
11570 std::string qualsString = difference.getAsString();
11571 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11572 << fnType.getUnqualifiedType()
11573 << qualsString
11574 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11575 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011576
David Majnemerb3e56542014-08-07 22:56:13 +000011577 if (resultType->isMemberPointerType())
11578 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11579 RequireCompleteType(LParenLoc, resultType, 0);
11580
John McCall0009fcc2011-04-26 20:42:42 +000011581 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011582 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011583 resultType, valueKind, RParenLoc);
11584
Alp Toker314cc812014-01-25 16:55:45 +000011585 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011586 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011587 return ExprError();
11588
Craig Topperc3ec1492014-05-26 06:22:03 +000011589 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011590 return ExprError();
11591
Richard Trieu9be9c682013-06-22 02:30:38 +000011592 if (CheckOtherCall(call, proto))
11593 return ExprError();
11594
John McCall0009fcc2011-04-26 20:42:42 +000011595 return MaybeBindToTemporary(call);
11596 }
11597
David Majnemerced8bdf2015-02-25 17:36:15 +000011598 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11599 return new (Context)
11600 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11601
John McCall4124c492011-10-17 18:40:02 +000011602 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011603 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011604 return ExprError();
11605
John McCall10eae182009-11-30 22:42:35 +000011606 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011607 CXXMethodDecl *Method = nullptr;
11608 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11609 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011610 if (isa<MemberExpr>(NakedMemExpr)) {
11611 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011612 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011613 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011614 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011615 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011616 } else {
11617 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011618 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011619
John McCall6e9f8f62009-12-03 04:06:58 +000011620 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011621 Expr::Classification ObjectClassification
11622 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11623 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011624
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011625 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011626 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11627 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011628
John McCall2d74de92009-12-01 22:10:20 +000011629 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011630 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011631 if (UnresExpr->hasExplicitTemplateArgs()) {
11632 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11633 TemplateArgs = &TemplateArgsBuffer;
11634 }
11635
John McCall10eae182009-11-30 22:42:35 +000011636 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11637 E = UnresExpr->decls_end(); I != E; ++I) {
11638
John McCall6e9f8f62009-12-03 04:06:58 +000011639 NamedDecl *Func = *I;
11640 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11641 if (isa<UsingShadowDecl>(Func))
11642 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11643
Douglas Gregor02824322011-01-26 19:30:28 +000011644
Francois Pichet64225792011-01-18 05:04:39 +000011645 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011646 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011647 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011648 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011649 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011650 // If explicit template arguments were provided, we can't call a
11651 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011652 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011653 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011654
John McCalla0296f72010-03-19 07:35:19 +000011655 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011656 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011657 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011658 } else {
John McCall10eae182009-11-30 22:42:35 +000011659 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011660 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011661 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011662 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011663 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011664 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011665 }
Mike Stump11289f42009-09-09 15:08:12 +000011666
John McCall10eae182009-11-30 22:42:35 +000011667 DeclarationName DeclName = UnresExpr->getMemberName();
11668
John McCall4124c492011-10-17 18:40:02 +000011669 UnbridgedCasts.restore();
11670
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011671 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011672 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011673 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011674 case OR_Success:
11675 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011676 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011677 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011678 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11679 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011680 // If FoundDecl is different from Method (such as if one is a template
11681 // and the other a specialization), make sure DiagnoseUseOfDecl is
11682 // called on both.
11683 // FIXME: This would be more comprehensively addressed by modifying
11684 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11685 // being used.
11686 if (Method != FoundDecl.getDecl() &&
11687 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11688 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011689 break;
11690
11691 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011692 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011693 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011694 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011695 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011696 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011697 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011698
11699 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011700 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011701 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011702 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011703 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011704 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011705
11706 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011707 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011708 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011709 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011710 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011711 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011712 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011713 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011714 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011715 }
11716
John McCall16df1e52010-03-30 21:47:33 +000011717 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011718
John McCall2d74de92009-12-01 22:10:20 +000011719 // If overload resolution picked a static member, build a
11720 // non-member call based on that function.
11721 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011722 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11723 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011724 }
11725
John McCall10eae182009-11-30 22:42:35 +000011726 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011727 }
11728
Alp Toker314cc812014-01-25 16:55:45 +000011729 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011730 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11731 ResultType = ResultType.getNonLValueExprType(Context);
11732
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011733 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011734 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011735 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011736 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011737
Eli Bendersky291a57e2014-09-25 23:59:08 +000011738 // (CUDA B.1): Check for invalid calls between targets.
11739 if (getLangOpts().CUDA) {
11740 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11741 if (CheckCUDATarget(Caller, Method)) {
11742 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11743 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11744 << IdentifyCUDATarget(Caller);
11745 return ExprError();
11746 }
11747 }
11748 }
11749
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011750 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000011751 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011752 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011753 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011754
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011755 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011756 // We only need to do this if there was actually an overload; otherwise
11757 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011758 if (!Method->isStatic()) {
11759 ExprResult ObjectArg =
11760 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11761 FoundDecl, Method);
11762 if (ObjectArg.isInvalid())
11763 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011764 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000011765 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011766
11767 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011768 const FunctionProtoType *Proto =
11769 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011770 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011771 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011772 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011773
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011774 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011775
Richard Smith55ce3522012-06-25 20:30:08 +000011776 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011777 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011778
Anders Carlsson47061ee2011-05-06 14:25:31 +000011779 if ((isa<CXXConstructorDecl>(CurContext) ||
11780 isa<CXXDestructorDecl>(CurContext)) &&
11781 TheCall->getMethodDecl()->isPure()) {
11782 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11783
Chandler Carruth59259262011-06-27 08:31:58 +000011784 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000011785 Diag(MemExpr->getLocStart(),
11786 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11787 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11788 << MD->getParent()->getDeclName();
11789
11790 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011791 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011792 }
John McCallb268a282010-08-23 23:25:46 +000011793 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011794}
11795
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011796/// BuildCallToObjectOfClassType - Build a call to an object of class
11797/// type (C++ [over.call.object]), which can end up invoking an
11798/// overloaded function call operator (@c operator()) or performing a
11799/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011800ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011801Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011802 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011803 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011804 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011805 if (checkPlaceholderForOverload(*this, Obj))
11806 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011807 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000011808
11809 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011810 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011811 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011812
Nico Weberb58e51c2014-11-19 05:21:39 +000011813 assert(Object.get()->getType()->isRecordType() &&
11814 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000011815 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011816
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011817 // C++ [over.call.object]p1:
11818 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011819 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011820 // candidate functions includes at least the function call
11821 // operators of T. The function call operators of T are obtained by
11822 // ordinary lookup of the name operator() in the context of
11823 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000011824 OverloadCandidateSet CandidateSet(LParenLoc,
11825 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000011826 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011827
John Wiegley01296292011-04-08 18:41:53 +000011828 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011829 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011830 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011831
John McCall27b18f82009-11-17 02:14:36 +000011832 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11833 LookupQualifiedName(R, Record->getDecl());
11834 R.suppressDiagnostics();
11835
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011836 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011837 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011838 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011839 Object.get()->Classify(Context),
11840 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011841 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011843
Douglas Gregorab7897a2008-11-19 22:57:39 +000011844 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011845 // In addition, for each (non-explicit in C++0x) conversion function
11846 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011847 //
11848 // operator conversion-type-id () cv-qualifier;
11849 //
11850 // where cv-qualifier is the same cv-qualification as, or a
11851 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011852 // denotes the type "pointer to function of (P1,...,Pn) returning
11853 // R", or the type "reference to pointer to function of
11854 // (P1,...,Pn) returning R", or the type "reference to function
11855 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011856 // is also considered as a candidate function. Similarly,
11857 // surrogate call functions are added to the set of candidate
11858 // functions for each conversion function declared in an
11859 // accessible base class provided the function is not hidden
11860 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000011861 const auto &Conversions =
11862 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11863 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011864 NamedDecl *D = *I;
11865 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11866 if (isa<UsingShadowDecl>(D))
11867 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011868
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011869 // Skip over templated conversion functions; they aren't
11870 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011871 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011872 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011873
John McCall6e9f8f62009-12-03 04:06:58 +000011874 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011875 if (!Conv->isExplicit()) {
11876 // Strip the reference type (if any) and then the pointer type (if
11877 // any) to get down to what might be a function type.
11878 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11879 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11880 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011881
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011882 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11883 {
11884 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011885 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011886 }
11887 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011888 }
Mike Stump11289f42009-09-09 15:08:12 +000011889
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011890 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11891
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011892 // Perform overload resolution.
11893 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011894 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011895 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011896 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011897 // Overload resolution succeeded; we'll build the appropriate call
11898 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011899 break;
11900
11901 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011902 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011903 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011904 << Object.get()->getType() << /*call*/ 1
11905 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011906 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011907 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011908 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011909 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011910 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011911 break;
11912
11913 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011914 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011915 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011916 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011917 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011918 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011919
11920 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011921 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011922 diag::err_ovl_deleted_object_call)
11923 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011924 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011925 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011926 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011927 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011928 break;
Mike Stump11289f42009-09-09 15:08:12 +000011929 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011930
Douglas Gregorb412e172010-07-25 18:17:45 +000011931 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011932 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011933
John McCall4124c492011-10-17 18:40:02 +000011934 UnbridgedCasts.restore();
11935
Craig Topperc3ec1492014-05-26 06:22:03 +000011936 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000011937 // Since there is no function declaration, this is one of the
11938 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011939 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011940 = cast<CXXConversionDecl>(
11941 Best->Conversions[0].UserDefined.ConversionFunction);
11942
Craig Topperc3ec1492014-05-26 06:22:03 +000011943 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11944 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011945 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11946 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011947 assert(Conv == Best->FoundDecl.getDecl() &&
11948 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011949 // We selected one of the surrogate functions that converts the
11950 // object parameter to a function pointer. Perform the conversion
11951 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011952
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011953 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011954 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011955 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11956 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011957 if (Call.isInvalid())
11958 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011959 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011960 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11961 CK_UserDefinedConversion, Call.get(),
11962 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011963
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011964 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011965 }
11966
Craig Topperc3ec1492014-05-26 06:22:03 +000011967 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011968
Douglas Gregorab7897a2008-11-19 22:57:39 +000011969 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11970 // that calls this method, using Object for the implicit object
11971 // parameter and passing along the remaining arguments.
11972 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011973
11974 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011975 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011976 return ExprError();
11977
Chandler Carruth8e543b32010-12-12 08:17:55 +000011978 const FunctionProtoType *Proto =
11979 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011980
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011981 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000011982
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011983 DeclarationNameInfo OpLocInfo(
11984 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11985 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011986 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011987 HadMultipleCandidates,
11988 OpLocInfo.getLoc(),
11989 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011990 if (NewFn.isInvalid())
11991 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011992
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011993 // Build the full argument list for the method call (the implicit object
11994 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000011995 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011996 MethodArgs[0] = Object.get();
11997 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11998
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011999 // Once we've built TheCall, all of the expressions are properly
12000 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012001 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012002 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12003 ResultTy = ResultTy.getNonLValueExprType(Context);
12004
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012005 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012006 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012007 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12008 ResultTy, VK, RParenLoc, false);
12009 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012010
Alp Toker314cc812014-01-25 16:55:45 +000012011 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012012 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012013
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012014 // We may have default arguments. If so, we need to allocate more
12015 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012016 if (Args.size() < NumParams)
12017 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012018
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012019 bool IsError = false;
12020
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012021 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012022 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012023 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012024 Best->FoundDecl, Method);
12025 if (ObjRes.isInvalid())
12026 IsError = true;
12027 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012028 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012029 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012030
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012031 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012032 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012033 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012034 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012035 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012036
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012037 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012038
John McCalldadc5752010-08-24 06:29:42 +000012039 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012040 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012041 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012042 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012043 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012044
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012045 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012046 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012047 } else {
John McCalldadc5752010-08-24 06:29:42 +000012048 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012049 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12050 if (DefArg.isInvalid()) {
12051 IsError = true;
12052 break;
12053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012054
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012055 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012056 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012057
12058 TheCall->setArg(i + 1, Arg);
12059 }
12060
12061 // If this is a variadic call, handle args passed through "...".
12062 if (Proto->isVariadic()) {
12063 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012064 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012065 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12066 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012067 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012068 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012069 }
12070 }
12071
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012072 if (IsError) return true;
12073
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012074 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012075
Richard Smith55ce3522012-06-25 20:30:08 +000012076 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012077 return true;
12078
John McCalle172be52010-08-24 06:09:16 +000012079 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012080}
12081
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012082/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012083/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012084/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012085ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012086Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12087 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012088 assert(Base->getType()->isRecordType() &&
12089 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012090
John McCall4124c492011-10-17 18:40:02 +000012091 if (checkPlaceholderForOverload(*this, Base))
12092 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012093
John McCallbc077cf2010-02-08 23:07:23 +000012094 SourceLocation Loc = Base->getExprLoc();
12095
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012096 // C++ [over.ref]p1:
12097 //
12098 // [...] An expression x->m is interpreted as (x.operator->())->m
12099 // for a class object x of type T if T::operator->() exists and if
12100 // the operator is selected as the best match function by the
12101 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012102 DeclarationName OpName =
12103 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012104 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012105 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012106
John McCallbc077cf2010-02-08 23:07:23 +000012107 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012108 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012109 return ExprError();
12110
John McCall27b18f82009-11-17 02:14:36 +000012111 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12112 LookupQualifiedName(R, BaseRecord->getDecl());
12113 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012114
12115 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012116 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012117 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012118 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012119 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012120
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012121 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12122
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012123 // Perform overload resolution.
12124 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012125 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012126 case OR_Success:
12127 // Overload resolution succeeded; we'll build the call below.
12128 break;
12129
12130 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012131 if (CandidateSet.empty()) {
12132 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012133 if (NoArrowOperatorFound) {
12134 // Report this specific error to the caller instead of emitting a
12135 // diagnostic, as requested.
12136 *NoArrowOperatorFound = true;
12137 return ExprError();
12138 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012139 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12140 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012141 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012142 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012143 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012144 }
12145 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012146 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012147 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012148 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012149 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012150
12151 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012152 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12153 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012154 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012155 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012156
12157 case OR_Deleted:
12158 Diag(OpLoc, diag::err_ovl_deleted_oper)
12159 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012160 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012161 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012162 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012163 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012164 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012165 }
12166
Craig Topperc3ec1492014-05-26 06:22:03 +000012167 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012168
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012169 // Convert the object parameter.
12170 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012171 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012172 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012173 Best->FoundDecl, Method);
12174 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012175 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012176 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012177
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012178 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012179 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012180 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012181 if (FnExpr.isInvalid())
12182 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012183
Alp Toker314cc812014-01-25 16:55:45 +000012184 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012185 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12186 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012187 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012188 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012189 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012190
Alp Toker314cc812014-01-25 16:55:45 +000012191 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012192 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012193
12194 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012195}
12196
Richard Smithbcc22fc2012-03-09 08:00:36 +000012197/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12198/// a literal operator described by the provided lookup results.
12199ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12200 DeclarationNameInfo &SuffixInfo,
12201 ArrayRef<Expr*> Args,
12202 SourceLocation LitEndLoc,
12203 TemplateArgumentListInfo *TemplateArgs) {
12204 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012205
Richard Smith100b24a2014-04-17 01:52:14 +000012206 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12207 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012208 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12209 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012210
Richard Smithbcc22fc2012-03-09 08:00:36 +000012211 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12212
Richard Smithbcc22fc2012-03-09 08:00:36 +000012213 // Perform overload resolution. This will usually be trivial, but might need
12214 // to perform substitutions for a literal operator template.
12215 OverloadCandidateSet::iterator Best;
12216 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12217 case OR_Success:
12218 case OR_Deleted:
12219 break;
12220
12221 case OR_No_Viable_Function:
12222 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12223 << R.getLookupName();
12224 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12225 return ExprError();
12226
12227 case OR_Ambiguous:
12228 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12229 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12230 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012231 }
12232
Richard Smithbcc22fc2012-03-09 08:00:36 +000012233 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012234 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12235 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012236 SuffixInfo.getLoc(),
12237 SuffixInfo.getInfo());
12238 if (Fn.isInvalid())
12239 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012240
12241 // Check the argument types. This should almost always be a no-op, except
12242 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012243 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012244 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012245 ExprResult InputInit = PerformCopyInitialization(
12246 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12247 SourceLocation(), Args[ArgIdx]);
12248 if (InputInit.isInvalid())
12249 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012250 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012251 }
12252
Alp Toker314cc812014-01-25 16:55:45 +000012253 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012254 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12255 ResultTy = ResultTy.getNonLValueExprType(Context);
12256
Richard Smithc67fdd42012-03-07 08:35:16 +000012257 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012258 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012259 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012260 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12261
Alp Toker314cc812014-01-25 16:55:45 +000012262 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012263 return ExprError();
12264
Craig Topperc3ec1492014-05-26 06:22:03 +000012265 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012266 return ExprError();
12267
12268 return MaybeBindToTemporary(UDL);
12269}
12270
Sam Panzer0f384432012-08-21 00:52:01 +000012271/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12272/// given LookupResult is non-empty, it is assumed to describe a member which
12273/// will be invoked. Otherwise, the function will be found via argument
12274/// dependent lookup.
12275/// CallExpr is set to a valid expression and FRS_Success returned on success,
12276/// otherwise CallExpr is set to ExprError() and some non-success value
12277/// is returned.
12278Sema::ForRangeStatus
12279Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12280 SourceLocation RangeLoc, VarDecl *Decl,
12281 BeginEndFunction BEF,
12282 const DeclarationNameInfo &NameInfo,
12283 LookupResult &MemberLookup,
12284 OverloadCandidateSet *CandidateSet,
12285 Expr *Range, ExprResult *CallExpr) {
12286 CandidateSet->clear();
12287 if (!MemberLookup.empty()) {
12288 ExprResult MemberRef =
12289 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12290 /*IsPtr=*/false, CXXScopeSpec(),
12291 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012292 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012293 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +000012294 /*TemplateArgs=*/nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012295 if (MemberRef.isInvalid()) {
12296 *CallExpr = ExprError();
12297 Diag(Range->getLocStart(), diag::note_in_for_range)
12298 << RangeLoc << BEF << Range->getType();
12299 return FRS_DiagnosticIssued;
12300 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012301 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012302 if (CallExpr->isInvalid()) {
12303 *CallExpr = ExprError();
12304 Diag(Range->getLocStart(), diag::note_in_for_range)
12305 << RangeLoc << BEF << Range->getType();
12306 return FRS_DiagnosticIssued;
12307 }
12308 } else {
12309 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012310 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012311 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012312 NestedNameSpecifierLoc(), NameInfo,
12313 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012314 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012315
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012316 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012317 CandidateSet, CallExpr);
12318 if (CandidateSet->empty() || CandidateSetError) {
12319 *CallExpr = ExprError();
12320 return FRS_NoViableFunction;
12321 }
12322 OverloadCandidateSet::iterator Best;
12323 OverloadingResult OverloadResult =
12324 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12325
12326 if (OverloadResult == OR_No_Viable_Function) {
12327 *CallExpr = ExprError();
12328 return FRS_NoViableFunction;
12329 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012330 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012331 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012332 OverloadResult,
12333 /*AllowTypoCorrection=*/false);
12334 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12335 *CallExpr = ExprError();
12336 Diag(Range->getLocStart(), diag::note_in_for_range)
12337 << RangeLoc << BEF << Range->getType();
12338 return FRS_DiagnosticIssued;
12339 }
12340 }
12341 return FRS_Success;
12342}
12343
12344
Douglas Gregorcd695e52008-11-10 20:40:00 +000012345/// FixOverloadedFunctionReference - E is an expression that refers to
12346/// a C++ overloaded function (possibly with some parentheses and
12347/// perhaps a '&' around it). We have resolved the overloaded function
12348/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012349/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012350Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012351 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012352 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012353 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12354 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012355 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012356 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012357
Douglas Gregor51c538b2009-11-20 19:42:02 +000012358 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012359 }
12360
Douglas Gregor51c538b2009-11-20 19:42:02 +000012361 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012362 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12363 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012364 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012365 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012366 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012367 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012368 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012369 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012370
12371 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012372 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012373 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012374 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012375 }
12376
Douglas Gregor51c538b2009-11-20 19:42:02 +000012377 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012378 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012379 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12381 if (Method->isStatic()) {
12382 // Do nothing: static member functions aren't any different
12383 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012384 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012385 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012386 // UnresolvedLookupExpr holding an overloaded member function
12387 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012388 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12389 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012390 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012391 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012392
John McCalld14a8642009-11-21 08:51:07 +000012393 assert(isa<DeclRefExpr>(SubExpr)
12394 && "fixed to something other than a decl ref");
12395 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12396 && "fixed to a member ref with no nested name qualifier");
12397
12398 // We have taken the address of a pointer to member
12399 // function. Perform the computation here so that we get the
12400 // appropriate pointer to member type.
12401 QualType ClassType
12402 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12403 QualType MemPtrType
12404 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12405
John McCall7decc9e2010-11-18 06:31:45 +000012406 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12407 VK_RValue, OK_Ordinary,
12408 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012409 }
12410 }
John McCall16df1e52010-03-30 21:47:33 +000012411 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12412 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012413 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012414 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012415
John McCalle3027922010-08-25 11:45:40 +000012416 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012417 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012418 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012419 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012420 }
John McCalld14a8642009-11-21 08:51:07 +000012421
12422 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012423 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012424 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012425 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012426 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12427 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012428 }
12429
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012430 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12431 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012432 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012433 Fn,
John McCall113bee02012-03-10 09:33:50 +000012434 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012435 ULE->getNameLoc(),
12436 Fn->getType(),
12437 VK_LValue,
12438 Found.getDecl(),
12439 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012440 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012441 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12442 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012443 }
12444
John McCall10eae182009-11-30 22:42:35 +000012445 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012446 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012447 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012448 if (MemExpr->hasExplicitTemplateArgs()) {
12449 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12450 TemplateArgs = &TemplateArgsBuffer;
12451 }
John McCall6b51f282009-11-23 01:53:49 +000012452
John McCall2d74de92009-12-01 22:10:20 +000012453 Expr *Base;
12454
John McCall7decc9e2010-11-18 06:31:45 +000012455 // If we're filling in a static method where we used to have an
12456 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012457 if (MemExpr->isImplicitAccess()) {
12458 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012459 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12460 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012461 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012462 Fn,
John McCall113bee02012-03-10 09:33:50 +000012463 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012464 MemExpr->getMemberLoc(),
12465 Fn->getType(),
12466 VK_LValue,
12467 Found.getDecl(),
12468 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012469 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012470 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12471 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012472 } else {
12473 SourceLocation Loc = MemExpr->getMemberLoc();
12474 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012475 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012476 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012477 Base = new (Context) CXXThisExpr(Loc,
12478 MemExpr->getBaseType(),
12479 /*isImplicit=*/true);
12480 }
John McCall2d74de92009-12-01 22:10:20 +000012481 } else
John McCallc3007a22010-10-26 07:05:15 +000012482 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012483
John McCall4adb38c2011-04-27 00:36:17 +000012484 ExprValueKind valueKind;
12485 QualType type;
12486 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12487 valueKind = VK_LValue;
12488 type = Fn->getType();
12489 } else {
12490 valueKind = VK_RValue;
12491 type = Context.BoundMemberTy;
12492 }
12493
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012494 MemberExpr *ME = MemberExpr::Create(Context, Base,
12495 MemExpr->isArrow(),
12496 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012497 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012498 Fn,
12499 Found,
12500 MemExpr->getMemberNameInfo(),
12501 TemplateArgs,
12502 type, valueKind, OK_Ordinary);
12503 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000012504 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012505 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012507
John McCallc3007a22010-10-26 07:05:15 +000012508 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012509}
12510
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012511ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012512 DeclAccessPair Found,
12513 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012514 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012515}