blob: fbf110b321e469932a6880ed6e8063c935977331 [file] [log] [blame]
Nick Lewycky5d9484d2013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor8e9bebd2008-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 Carruth55fc8732012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
David Majnemere9f6f332013-09-16 22:44:20 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-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 Gregor661b4932010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smithb8590f32012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000035#include <algorithm>
Stephen Hines6bcf27b2014-05-29 04:14:42 -070036#include <cstdlib>
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000037
Stephen Hines176edba2014-12-01 14:53:08 -080038using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000039using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000040
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000041/// A convenience routine for creating a decayed reference to a function.
John Wiegley429bb272011-04-08 18:41:53 +000042static ExprResult
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000043CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44 bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000045 SourceLocation Loc = SourceLocation(),
46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith82f145d2013-05-04 06:44:46 +000047 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid570a922013-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 Smith82f145d2013-05-04 06:44:46 +000056 return ExprError();
John McCallf4b88a42012-03-10 09:33:50 +000057 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000058 VK_LValue, Loc, LocInfo);
59 if (HadMultipleCandidates)
60 DRE->setHadMultipleCandidates(true);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000061
62 S.MarkDeclRefReferenced(DRE);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000063
Stephen Hinesc568f1e2014-07-21 00:47:37 -070064 ExprResult E = DRE;
65 E = S.DefaultFunctionArrayConversion(E.get());
John Wiegley429bb272011-04-08 18:41:53 +000066 if (E.isInvalid())
67 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000068 return E;
John McCallf89e55a2010-11-18 06:31:45 +000069}
70
John McCall120d63c2010-08-24 20:38:10 +000071static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000073 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000074 bool CStyle,
75 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000076
Fariborz Jahaniand97f5582011-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 McCall120d63c2010-08-24 20:38:10 +000082static OverloadingResult
83IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84 UserDefinedConversionSequence& User,
85 OverloadCandidateSet& Conversions,
Douglas Gregor1ce55092013-11-07 22:34:54 +000086 bool AllowExplicit,
87 bool AllowObjCConversionOnExplicit);
John McCall120d63c2010-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 Gregor8e9bebd2008-10-21 16:13:35 +0000105/// GetConversionRank - Retrieve the implicit conversion rank
106/// corresponding to the given implicit conversion kind.
Stephen Hines176edba2014-12-01 14:53:08 -0800107ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor8e9bebd2008-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 Gregor43c79c22009-12-09 00:47:37 +0000115 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000116 ICR_Promotion,
117 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000118 ICR_Promotion,
119 ICR_Conversion,
120 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000126 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000127 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000128 ICR_Conversion,
129 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000130 ICR_Complex_Real_Conversion,
131 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000132 ICR_Conversion,
133 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-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.
Stephen Hines176edba2014-12-01 14:53:08 -0800140static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000141 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000142 "No conversion",
143 "Lvalue-to-rvalue",
144 "Array-to-pointer",
145 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000146 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000147 "Qualification",
148 "Integral promotion",
149 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000150 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000151 "Integral conversion",
152 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000153 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000154 "Floating-integral conversion",
155 "Pointer conversion",
156 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000157 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000158 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000159 "Derived-to-base conversion",
160 "Vector conversion",
161 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000162 "Complex-real conversion",
163 "Block Pointer conversion",
Stephen Hines176edba2014-12-01 14:53:08 -0800164 "Transparent Union Conversion",
John McCallf85e1932011-06-15 23:02:42 +0000165 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000166 };
167 return Name[Kind];
168}
169
Douglas Gregor60d62c22008-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 Gregora9bff302010-02-28 18:30:25 +0000176 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000177 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000178 ReferenceBinding = false;
179 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000180 IsLvalueReference = true;
181 BindsToFunctionLvalue = false;
182 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000183 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000184 ObjCLifetimeConversionBinding = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700185 CopyConstructor = nullptr;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000186}
187
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +0000204/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000205/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000206bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-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 Gregorad323a82010-01-27 03:51:04 +0000211 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000212 (getFromType()->isPointerType() ||
213 getFromType()->isObjCObjectPointerType() ||
214 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000215 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-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 Gregorbc0805a2008-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 Stump1eb44332009-09-09 15:08:12 +0000226bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000227StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000228isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000229 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000230 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-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 Gregorf9af5242011-04-15 20:45:44 +0000238 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000239 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000240 return ToPtrType->getPointeeType()->isVoidType();
241
242 return false;
243}
244
Richard Smith4c3fc9b2012-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 Smithf6028062012-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 Smith4c3fc9b2012-01-18 05:21:49 +0000277NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000278StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
279 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000280 APValue &ConstantValue,
281 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000282 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-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) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700289 // '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 Smith4c3fc9b2012-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:
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700306 FloatingIntegralConversion:
Richard Smith4c3fc9b2012-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 Smithf6028062012-03-23 23:55:39 +0000326 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-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 Smithf6028062012-03-23 23:55:39 +0000356 if (ConvertStatus & llvm::APFloat::opOverflow) {
357 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000358 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000359 }
Richard Smith4c3fc9b2012-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.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700371 case ICK_Integral_Conversion:
372 IntegralConversion: {
Richard Smith4c3fc9b2012-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 Smithcd65f492012-06-13 01:07:41 +0000381 (FromWidth == ToWidth && FromSigned != ToSigned) ||
382 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-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 Smithcd65f492012-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 Smith5d7700e2012-06-19 21:28:35 +0000389 }
390 bool Narrowing = false;
391 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000392 // Negative -> unsigned is narrowing. Otherwise, more bits is never
393 // narrowing.
394 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000395 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000396 } else {
Richard Smith4c3fc9b2012-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 Smith5d7700e2012-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 Smith4c3fc9b2012-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 Gregor2f8b0cc2013-11-08 02:16:10 +0000426/// dump - Print this standard conversion sequence to standard
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000427/// error. Useful for debugging overloading issues.
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +0000428void StandardConversionSequence::dump() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000429 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000430 bool PrintedSomething = false;
431 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000432 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000433 PrintedSomething = true;
434 }
435
436 if (Second != ICK_Identity) {
437 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000438 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000439 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000440 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000441
442 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000443 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000444 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000445 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000446 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000447 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000448 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000449 PrintedSomething = true;
450 }
451
452 if (Third != ICK_Identity) {
453 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000454 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000456 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000457 PrintedSomething = true;
458 }
459
460 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000461 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000462 }
463}
464
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +0000465/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000466/// error. Useful for debugging overloading issues.
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +0000467void UserDefinedConversionSequence::dump() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000468 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000469 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +0000470 Before.dump();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000471 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000472 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000473 if (ConversionFunction)
474 OS << '\'' << *ConversionFunction << '\'';
475 else
476 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000477 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000478 OS << " -> ";
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +0000479 After.dump();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 }
481}
482
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +0000483/// dump - Print this implicit conversion sequence to standard
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000484/// error. Useful for debugging overloading issues.
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +0000485void ImplicitConversionSequence::dump() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000486 raw_ostream &OS = llvm::errs();
Richard Smith798186a2013-09-06 22:30:28 +0000487 if (isStdInitializerListElement())
488 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000489 switch (ConversionKind) {
490 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000491 OS << "Standard conversion: ";
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +0000492 Standard.dump();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000493 break;
494 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000495 OS << "User-defined conversion: ";
Douglas Gregor2f8b0cc2013-11-08 02:16:10 +0000496 UserDefined.dump();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000497 break;
498 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000499 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000500 break;
John McCall1d318332010-01-12 00:44:57 +0000501 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000502 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000503 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000505 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 break;
507 }
508
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000509 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000510}
511
John McCall1d318332010-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 Gregora9333192010-05-08 17:41:32 +0000527namespace {
Larisse Voufo43847122013-07-19 23:00:19 +0000528 // Structure used by DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000529 // template argument information.
530 struct DFIArguments {
Douglas Gregora9333192010-05-08 17:41:32 +0000531 TemplateArgument FirstArg;
532 TemplateArgument SecondArg;
533 };
Larisse Voufo43847122013-07-19 23:00:19 +0000534 // Structure used by DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000535 // template parameter and template argument information.
536 struct DFIParamWithArguments : DFIArguments {
537 TemplateParameter Param;
538 };
Douglas Gregora9333192010-05-08 17:41:32 +0000539}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000540
Douglas Gregora9333192010-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.
Stephen Hines176edba2014-12-01 14:53:08 -0800543DeductionFailureInfo
544clang::MakeDeductionFailureInfo(ASTContext &Context,
545 Sema::TemplateDeductionResult TDK,
546 TemplateDeductionInfo &Info) {
Larisse Voufo43847122013-07-19 23:00:19 +0000547 DeductionFailureInfo Result;
Douglas Gregora9333192010-05-08 17:41:32 +0000548 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000549 Result.HasDiagnostic = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700550 Result.Data = nullptr;
Douglas Gregora9333192010-05-08 17:41:32 +0000551 switch (TDK) {
552 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000553 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000554 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000555 case Sema::TDK_TooManyArguments:
556 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000557 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000558
Douglas Gregora9333192010-05-08 17:41:32 +0000559 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000560 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000561 Result.Data = Info.Param.getOpaqueValue();
562 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000563
Richard Smith29805ca2013-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 Gregora9333192010-05-08 17:41:32 +0000573 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000574 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-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 Gregora9333192010-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 Takumidfbb02a2011-01-27 07:10:08 +0000583
Douglas Gregora9333192010-05-08 17:41:32 +0000584 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000585 Result.Data = Info.take();
Richard Smithb8590f32012-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 Gregorec20f462010-05-08 20:07:26 +0000592 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000593
Douglas Gregora9333192010-05-08 17:41:32 +0000594 case Sema::TDK_FailedOverloadResolution:
Richard Smith0efa62f2013-01-31 04:03:12 +0000595 Result.Data = Info.Expression;
596 break;
597
Richard Smith29805ca2013-01-31 05:19:49 +0000598 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000599 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000600 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000601
Douglas Gregora9333192010-05-08 17:41:32 +0000602 return Result;
603}
John McCall1d318332010-01-12 00:44:57 +0000604
Larisse Voufo43847122013-07-19 23:00:19 +0000605void DeductionFailureInfo::Destroy() {
Douglas Gregora9333192010-05-08 17:41:32 +0000606 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
607 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000608 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000609 case Sema::TDK_InstantiationDepth:
610 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000611 case Sema::TDK_TooManyArguments:
612 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000613 case Sema::TDK_InvalidExplicitArguments:
Richard Smith29805ca2013-01-31 05:19:49 +0000614 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000615 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000616
Douglas Gregora9333192010-05-08 17:41:32 +0000617 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000618 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000619 case Sema::TDK_NonDeducedMismatch:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000620 // FIXME: Destroy the data?
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700621 Data = nullptr;
Douglas Gregora9333192010-05-08 17:41:32 +0000622 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000623
624 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000625 // FIXME: Destroy the template argument list?
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700626 Data = nullptr;
Richard Smithb8590f32012-05-07 09:03:25 +0000627 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
628 Diag->~PartialDiagnosticAt();
629 HasDiagnostic = false;
630 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000631 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000632
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000633 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000634 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000635 break;
636 }
637}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000638
Larisse Voufo43847122013-07-19 23:00:19 +0000639PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smithb8590f32012-05-07 09:03:25 +0000640 if (HasDiagnostic)
641 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700642 return nullptr;
Richard Smithb8590f32012-05-07 09:03:25 +0000643}
644
Larisse Voufo43847122013-07-19 23:00:19 +0000645TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregora9333192010-05-08 17:41:32 +0000646 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
647 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000648 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000649 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000650 case Sema::TDK_TooManyArguments:
651 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000652 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000653 case Sema::TDK_NonDeducedMismatch:
654 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000655 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000656
Douglas Gregora9333192010-05-08 17:41:32 +0000657 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000658 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000659 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000660
661 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000662 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000663 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000664
Douglas Gregora9333192010-05-08 17:41:32 +0000665 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000666 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000667 break;
668 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000669
Douglas Gregora9333192010-05-08 17:41:32 +0000670 return TemplateParameter();
671}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000672
Larisse Voufo43847122013-07-19 23:00:19 +0000673TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregorec20f462010-05-08 20:07:26 +0000674 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith29805ca2013-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:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700686 return nullptr;
Douglas Gregorec20f462010-05-08 20:07:26 +0000687
Richard Smith29805ca2013-01-31 05:19:49 +0000688 case Sema::TDK_SubstitutionFailure:
689 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000690
Richard Smith29805ca2013-01-31 05:19:49 +0000691 // Unhandled
692 case Sema::TDK_MiscellaneousDeductionFailure:
693 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000694 }
695
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700696 return nullptr;
Douglas Gregorec20f462010-05-08 20:07:26 +0000697}
698
Larisse Voufo43847122013-07-19 23:00:19 +0000699const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregora9333192010-05-08 17:41:32 +0000700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
701 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000702 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000707 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000708 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000709 case Sema::TDK_FailedOverloadResolution:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700710 return nullptr;
Douglas Gregora9333192010-05-08 17:41:32 +0000711
Douglas Gregora9333192010-05-08 17:41:32 +0000712 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000713 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000714 case Sema::TDK_NonDeducedMismatch:
715 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000716
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000717 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000718 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000719 break;
720 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000721
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700722 return nullptr;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000723}
Douglas Gregora9333192010-05-08 17:41:32 +0000724
Larisse Voufo43847122013-07-19 23:00:19 +0000725const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregora9333192010-05-08 17:41:32 +0000726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000728 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000733 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000734 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000735 case Sema::TDK_FailedOverloadResolution:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700736 return nullptr;
Douglas Gregora9333192010-05-08 17:41:32 +0000737
Douglas Gregora9333192010-05-08 17:41:32 +0000738 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000739 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000742
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000743 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000744 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000745 break;
746 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000747
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700748 return nullptr;
Douglas Gregora9333192010-05-08 17:41:32 +0000749}
750
Larisse Voufo43847122013-07-19 23:00:19 +0000751Expr *DeductionFailureInfo::getExpr() {
Richard Smith0efa62f2013-01-31 04:03:12 +0000752 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
753 Sema::TDK_FailedOverloadResolution)
754 return static_cast<Expr*>(Data);
755
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700756 return nullptr;
Richard Smith0efa62f2013-01-31 04:03:12 +0000757}
758
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000759void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000760 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000761 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
762 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000763 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
764 i->DeductionFailure.Destroy();
765 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000766}
767
768void OverloadCandidateSet::clear() {
769 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000770 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000771 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000772 Functions.clear();
773}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000774
John McCall5acb0c92011-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.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700806static bool
807checkPlaceholderForOverload(Sema &S, Expr *&E,
808 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall5acb0c92011-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
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700827 E = result.get();
John McCall5acb0c92011-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 Gribenko9e00f122013-05-09 21:02:07 +0000837static bool checkArgPlaceholdersForOverload(Sema &S,
838 MultiExprArg Args,
John McCall5acb0c92011-10-17 18:40:02 +0000839 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000840 for (unsigned i = 0, e = Args.size(); i != e; ++i)
841 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall5acb0c92011-10-17 18:40:02 +0000842 return true;
843
844 return false;
845}
846
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000847// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-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 McCall871b2e72009-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 Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +0000863// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000864//
John McCall51fa86f2009-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 Gregor8e9bebd2008-10-21 16:13:35 +0000869//
John McCall51fa86f2009-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 Gregor8e9bebd2008-10-21 16:13:35 +0000874// signature), IsOverload returns false and MatchedDecl will be set to
875// point to the FunctionDecl for #2.
John McCallad00b772010-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 McCall871b2e72009-12-09 03:35:25 +0000881Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000882Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
883 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000884 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000885 I != E; ++I) {
John McCallad00b772010-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 McCall78037ac2013-04-03 21:19:47 +0000905 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
906 !New->getFriendObjectKind();
John McCallad00b772010-06-16 08:42:20 +0000907
Stephen Hines651f13c2014-04-23 16:59:28 -0700908 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCallad00b772010-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
Stephen Hines651f13c2014-04-23 16:59:28 -0700915 if (!isa<FunctionTemplateDecl>(OldD) &&
916 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola90cc3902013-04-15 12:49:13 +0000917 continue;
918
John McCall871b2e72009-12-09 03:35:25 +0000919 Match = *I;
920 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000921 }
John McCalld7945c62010-11-10 03:01:53 +0000922 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-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 McCalld7945c62010-11-10 03:01:53 +0000926 } else if (isa<TagDecl>(OldD)) {
927 // We can always overload with tags by hiding them.
John McCall9f54ad42009-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 McCall68263142009-11-18 22:49:29 +0000933 // (C++ 13p1):
934 // Only function declarations can be overloaded; object and type
935 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000936 Match = *I;
937 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000938 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000939 }
John McCall68263142009-11-18 22:49:29 +0000940
John McCall871b2e72009-12-09 03:35:25 +0000941 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000942}
943
Richard Smithaa4bc182013-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 Espindola78eeba82012-12-28 14:21:58 +0000948 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000949
David Majnemere9f6f332013-09-16 22:44:20 +0000950 // MSVCRT user defined entry points cannot be overloaded.
951 if (New->isMSVCRTEntryPoint())
952 return false;
953
John McCall68263142009-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.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700960 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall68263142009-11-18 22:49:29 +0000961 return true;
962
963 // Is the function New an overload of the function Old?
Richard Smithaa4bc182013-06-30 09:48:50 +0000964 QualType OldQType = Context.getCanonicalType(Old->getType());
965 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall68263142009-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
Stephen Hines651f13c2014-04-23 16:59:28 -0700977 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
978 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-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 &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700984 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall68263142009-11-18 22:49:29 +0000985 OldType->isVariadic() != NewType->isVariadic() ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700986 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall68263142009-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 McCallad00b772010-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 Smithaa4bc182013-06-30 09:48:50 +00001002 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1003 OldTemplate->getTemplateParameters(),
1004 false, TPL_TemplateMatch) ||
Stephen Hines651f13c2014-04-23 16:59:28 -07001005 OldType->getReturnType() != NewType->getReturnType()))
John McCall68263142009-11-18 22:49:29 +00001006 return true;
1007
1008 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001009 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-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 Smith21c8fa82013-01-14 05:37:29 +00001016 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1017 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001018 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-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 Smithaa4bc182013-06-30 09:48:50 +00001030 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith21c8fa82013-01-14 05:37:29 +00001031 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithaa4bc182013-06-30 09:48:50 +00001032 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith21c8fa82013-01-14 05:37:29 +00001033 }
1034 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001035 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001036
Richard Smith21c8fa82013-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 Majnemer62e93702013-11-03 23:51:28 +00001041 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith21c8fa82013-01-14 05:37:29 +00001042 unsigned NewQuals = NewMethod->getTypeQualifiers();
Stephen Hines176edba2014-12-01 14:53:08 -08001043 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithdb2fe732013-06-25 18:46:26 +00001044 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001045 NewQuals |= Qualifiers::Const;
David Majnemer62e93702013-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 Smith21c8fa82013-01-14 05:37:29 +00001051 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001052 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001053
Stephen Hines651f13c2014-04-23 16:59:28 -07001054 // 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);
1066 if (NewID != OldID)
1067 return true;
1068 }
1069
John McCall68263142009-11-18 22:49:29 +00001070 // The signatures match; this is not an overload.
1071 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001072}
1073
Argyrios Kyrtzidis572bbec2011-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 Redlcf15cef2011-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 Gregor1ce55092013-11-07 22:34:54 +00001093 bool AllowObjCWritebackConversion,
1094 bool AllowObjCConversionOnExplicit) {
Sebastian Redlcf15cef2011-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.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001105 OverloadCandidateSet Conversions(From->getExprLoc(),
1106 OverloadCandidateSet::CSK_Normal);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001107 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1108 Conversions, AllowExplicit,
1109 AllowObjCConversionOnExplicit)) {
1110 case OR_Success:
1111 case OR_Deleted:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001112 ICS.setUserDefined();
Stephen Hines651f13c2014-04-23 16:59:28 -07001113 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redlcf15cef2011-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 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001140 break;
1141
1142 case OR_Ambiguous:
Sebastian Redlcf15cef2011-12-22 18:58:38 +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);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001150 break;
1151
1152 // Fall through.
1153 case OR_No_Viable_Function:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001154 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001155 break;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001156 }
1157
1158 return ICS;
1159}
1160
Douglas Gregor27c8dc02008-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 Gregor8e9bebd2008-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 Gregor225c41e2008-11-03 19:09:14 +00001179///
1180/// If @p SuppressUserConversions, then user-defined conversions are
1181/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001182/// If @p AllowExplicit, then explicit user-defined conversions are
1183/// permitted.
John McCallf85e1932011-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 McCall120d63c2010-08-24 20:38:10 +00001188static ImplicitConversionSequence
1189TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1190 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001191 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001192 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001193 bool CStyle,
Douglas Gregor1ce55092013-11-07 22:34:54 +00001194 bool AllowObjCWritebackConversion,
1195 bool AllowObjCConversionOnExplicit) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001196 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001197 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001198 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001199 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001200 return ICS;
1201 }
1202
David Blaikie4e4d0842012-03-11 07:00:24 +00001203 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001204 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001205 return ICS;
1206 }
1207
Douglas Gregor604eb652010-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 McCall120d63c2010-08-24 20:38:10 +00001217 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1218 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001219 ICS.setStandard();
1220 ICS.Standard.setAsIdentityConversion();
1221 ICS.Standard.setFromType(FromType);
1222 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001223
Douglas Gregor3fbaf3e2010-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.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001228 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001229
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001230 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001231 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001232 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001233
Douglas Gregor604eb652010-08-11 02:15:33 +00001234 return ICS;
1235 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001236
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001237 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1238 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor1ce55092013-11-07 22:34:54 +00001239 AllowObjCWritebackConversion,
1240 AllowObjCConversionOnExplicit);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001241}
1242
John McCallf85e1932011-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) {
Stephen Hines176edba2014-12-01 14:53:08 -08001250 return ::TryImplicitConversion(*this, From, ToType,
1251 SuppressUserConversions, AllowExplicit,
1252 InOverloadResolution, CStyle,
1253 AllowObjCWritebackConversion,
1254 /*AllowObjCConversionOnExplicit=*/false);
John McCall120d63c2010-08-24 20:38:10 +00001255}
1256
Douglas Gregor575c63a2010-04-16 22:27:05 +00001257/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001258/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-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 Wiegley429bb272011-04-08 18:41:53 +00001262ExprResult
1263Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001264 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001265 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001266 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001267}
1268
John Wiegley429bb272011-04-08 18:41:53 +00001269ExprResult
1270Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001271 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001272 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001273 if (checkPlaceholderForOverload(*this, From))
1274 return ExprError();
1275
John McCallf85e1932011-06-15 23:02:42 +00001276 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1277 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001278 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001279 (Action == AA_Passing || Action == AA_Sending);
Stephen Hines651f13c2014-04-23 16:59:28 -07001280 if (getLangOpts().ObjC1)
1281 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1282 ToType, From->getType(), From);
Stephen Hines176edba2014-12-01 14:53:08 -08001283 ICS = ::TryImplicitConversion(*this, From, ToType,
1284 /*SuppressUserConversions=*/false,
1285 AllowExplicit,
1286 /*InOverloadResolution=*/false,
1287 /*CStyle=*/false,
1288 AllowObjCWritebackConversion,
1289 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001290 return PerformImplicitConversion(From, ToType, ICS, Action);
1291}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001292
1293/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001294/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001295bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1296 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001297 if (Context.hasSameUnqualifiedType(FromType, ToType))
1298 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001299
John McCall00ccbef2010-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 Gregor43c79c22009-12-09 00:47:37 +00001322
John McCall00ccbef2010-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 Gregor43c79c22009-12-09 00:47:37 +00001338 return true;
1339}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001340
Douglas Gregorfb4a5432010-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07001346static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001347 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07001354 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregorfb4a5432010-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 Takumidfbb02a2011-01-27 07:10:08 +00001363
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001364 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001365 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001366 ICK = ICK_Vector_Splat;
1367 return true;
1368 }
1369 }
Douglas Gregor255210e2010-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()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001376 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1377 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001378 ICK = ICK_Vector_Conversion;
1379 return true;
1380 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001381 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001382
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001383 return false;
1384}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001385
Douglas Gregor7d000652012-04-12 20:48:09 +00001386static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1387 bool InOverloadResolution,
1388 StandardConversionSequence &SCS,
1389 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001390
Douglas Gregor60d62c22008-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 McCall120d63c2010-08-24 20:38:10 +00001399static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1400 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001401 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001402 bool CStyle,
1403 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001404 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001405
Douglas Gregor60d62c22008-10-31 16:23:19 +00001406 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001407 SCS.setAsIdentityConversion();
Douglas Gregor45920e82008-12-19 17:40:08 +00001408 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001409 SCS.setFromType(FromType);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001410 SCS.CopyConstructor = nullptr;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001411
Douglas Gregorf9201e02009-02-11 23:02:49 +00001412 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001413 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001414 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001415 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001416 return false;
1417
Mike Stump1eb44332009-09-09 15:08:12 +00001418 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001419 }
1420
Douglas Gregor8e9bebd2008-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 McCall120d63c2010-08-24 20:38:10 +00001425 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001426 DeclAccessPair AccessPair;
1427 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001428 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001429 AccessPair)) {
Douglas Gregorad4e02f2010-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();
Stephen Hines176edba2014-12-01 14:53:08 -08001433 SCS.setFromType(FromType);
Douglas Gregor1be8eec2011-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 Carruth18e04612011-06-18 01:19:03 +00001441 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-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 Gregorad4e02f2010-04-29 18:24:40 +00001446 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001447
Chandler Carruth90434232011-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 Carruthfc5c8fc2011-03-29 18:38:10 +00001462 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1463 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1464 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001465 "Non-address-of operator for overloaded function expression");
1466 FromType = S.Context.getPointerType(FromType);
1467 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001468
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001469 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001470 assert(S.Context.hasSameType(
1471 FromType,
1472 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001473 } else {
1474 return false;
1475 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001476 }
John McCall21480112011-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 McCall7eb0a9e2010-11-24 05:12:34 +00001481 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001482 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001483 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001484 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001485
Douglas Gregorf7ecc302012-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 Gregor8e9bebd2008-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 Gregorf9201e02009-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 Gregor60d62c22008-10-31 16:23:19 +00001496 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001497 } else if (FromType->isArrayType()) {
1498 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001499 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-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 McCall120d63c2010-08-24 20:38:10 +00001504 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001505
John McCall120d63c2010-08-24 20:38:10 +00001506 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001507 // This conversion is deprecated in C++03 (D.4)
Douglas Gregora9bff302010-02-28 18:30:25 +00001508 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-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 Gregor60d62c22008-10-31 16:23:19 +00001514 SCS.Second = ICK_Identity;
1515 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001516 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001517 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001518 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001519 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001520 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001521 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001522 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-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 McCall120d63c2010-08-24 20:38:10 +00001527 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001528 } else {
1529 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001530 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001531 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001532 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-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 Gregorf9201e02009-02-11 23:02:49 +00001538 // For overloading in C, this can also be a "compatible-type"
1539 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001540 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001541 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001542 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001543 // The unqualified versions of the types are the same: there's no
1544 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001545 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001546 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001547 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001548 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001549 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001550 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001551 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001552 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001553 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001554 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001555 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001556 SCS.Second = ICK_Complex_Promotion;
1557 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-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 Gregor1274ccd2010-10-08 23:50:27 +00001567 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001568 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001569 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001570 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001571 FromType = ToType.getUnqualifiedType();
Richard Smith42860f12013-05-10 20:29:50 +00001572 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001573 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001574 SCS.Second = ICK_Complex_Conversion;
1575 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001576 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1577 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-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 Gregor0c293ea2010-06-22 23:07:26 +00001581 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001582 // Floating point conversions (C++ 4.8).
1583 SCS.Second = ICK_Floating_Conversion;
1584 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001585 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001586 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001587 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001588 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001589 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001590 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001591 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001592 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-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 McCall120d63c2010-08-24 20:38:10 +00001597 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1598 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001599 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001600 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001601 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001602 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001603 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001604 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001605 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001606 SCS.Second = ICK_Pointer_Member;
Stephen Hines651f13c2014-04-23 16:59:28 -07001607 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001608 SCS.Second = SecondICK;
1609 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001610 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001611 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001612 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001613 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001614 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001615 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001616 // Treat a conversion that strips "noreturn" as an identity conversion.
1617 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-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 Gregor7d000652012-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 Gregorf7ecc302012-04-12 17:51:55 +00001626 // appropriately.
1627 return true;
Guy Benyei6959acd2013-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 Gregor8e9bebd2008-10-21 16:13:35 +00001633 } else {
1634 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001635 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001636 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001637 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001638
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001639 QualType CanonFrom;
1640 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001641 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001642 bool ObjCLifetimeConversion;
1643 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1644 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001645 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001646 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001647 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001648 CanonFrom = S.Context.getCanonicalType(FromType);
1649 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001650 } else {
1651 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001652 SCS.Third = ICK_Identity;
1653
Mike Stump1eb44332009-09-09 15:08:12 +00001654 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-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 McCall120d63c2010-08-24 20:38:10 +00001658 CanonFrom = S.Context.getCanonicalType(FromType);
1659 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001660 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001661 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault5509f372013-02-26 21:15:54 +00001662 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001663 FromType = ToType;
1664 CanonFrom = CanonTo;
1665 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001666 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001667 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-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 Gregor27c8dc02008-10-29 00:13:59 +00001671 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001672 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001673
Douglas Gregor60d62c22008-10-31 16:23:19 +00001674 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001675}
Fariborz Jahaniand97f5582011-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07001690 for (const auto *it : UD->fields()) {
John McCallf85e1932011-06-15 23:02:42 +00001691 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1692 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001693 ToType = it->getType();
1694 return true;
1695 }
1696 }
1697 return false;
1698}
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +00001704bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001705 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001706 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001707 if (!To) {
1708 return false;
1709 }
Douglas Gregor8e9bebd2008-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 Gregoraa74a1e2010-02-02 20:10:50 +00001716 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1717 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +00001722 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001723 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001724 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001725 }
1726
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001727 return To->getKind() == BuiltinType::UInt;
1728 }
1729
Richard Smithe7ff9192012-09-13 21:18:54 +00001730 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-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 Gregor0b8ddb92010-10-21 18:04:08 +00001736 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001737 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001738 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-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 Gregor0b8ddb92010-10-21 18:04:08 +00001741 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-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 Gregor1274ccd2010-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 Smithe7ff9192012-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 Gregor0b8ddb92010-10-21 18:04:08 +00001762 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001763 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001764 !RequireCompleteType(From->getLocStart(), FromType, 0))
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001765 return Context.hasSameUnqualifiedType(
1766 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001767 }
John McCall842aef82009-12-09 09:09:27 +00001768
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001769 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-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 Gregor0b8ddb92010-10-21 18:04:08 +00001773 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001774 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001775 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001776 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001777 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001778 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001779 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001780 // Determine whether the type we're converting from is signed or
1781 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001782 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001783 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001784
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +00001787 QualType PromoteTypes[6] = {
1788 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001789 Context.LongTy, Context.UnsignedLongTy ,
1790 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001791 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001792 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001793 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1794 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001795 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-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 Gregora4923eb2009-11-16 21:35:15 +00001800 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-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 Stump390b4cc2009-05-16 07:39:55 +00001812 // FIXME: We should delay checking of bit-fields until we actually perform the
1813 // conversion.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001814 if (From) {
John McCall993f43f2013-05-06 21:39:12 +00001815 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001816 llvm::APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001817 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001818 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001819 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001820 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Douglas Gregor86f19402008-12-20 23:49:58 +00001822 // Are we promoting to an int from a bitfield that fits in an int?
1823 if (BitWidth < ToSize ||
1824 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1825 return To->getKind() == BuiltinType::Int;
1826 }
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Douglas Gregor86f19402008-12-20 23:49:58 +00001828 // Are we promoting to an unsigned int from an unsigned bitfield
1829 // that fits into an unsigned int?
1830 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1831 return To->getKind() == BuiltinType::UInt;
1832 }
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Douglas Gregor86f19402008-12-20 23:49:58 +00001834 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001835 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001836 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001837 }
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Douglas Gregor8e9bebd2008-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 Redl07779722008-10-31 14:43:28 +00001841 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001842 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001843 }
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +00001851bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001852 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1853 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-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 Gregor8e9bebd2008-10-21 16:13:35 +00001856 if (FromBuiltin->getKind() == BuiltinType::Float &&
1857 ToBuiltin->getKind() == BuiltinType::Double)
1858 return true;
1859
Douglas Gregor5cdf8212009-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 Blaikie4e4d0842012-03-11 07:00:24 +00001863 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001864 (FromBuiltin->getKind() == BuiltinType::Float ||
1865 FromBuiltin->getKind() == BuiltinType::Double) &&
1866 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1867 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001868
1869 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001870 if (!getLangOpts().NativeHalfType &&
1871 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001872 ToBuiltin->getKind() == BuiltinType::Float)
1873 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001874 }
1875
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001876 return false;
1877}
1878
Douglas Gregor5cdf8212009-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 Gregorb7b5d132009-02-12 00:26:06 +00001883/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001884bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001885 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001886 if (!FromComplex)
1887 return false;
1888
John McCall183700f2009-09-21 23:43:11 +00001889 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001890 if (!ToComplex)
1891 return false;
1892
1893 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001894 ToComplex->getElementType()) ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001895 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001896 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001897}
1898
Douglas Gregorcb7de522008-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 McCallf85e1932011-06-15 23:02:42 +00001904///
Mike Stump1eb44332009-09-09 15:08:12 +00001905static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001906BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001907 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001908 ASTContext &Context,
1909 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001910 assert((FromPtr->getTypeClass() == Type::Pointer ||
1911 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1912 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001913
John McCallf85e1932011-06-15 23:02:42 +00001914 /// Conversions to 'id' subsume cv-qualifier conversions.
1915 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001916 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001917
1918 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001919 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001920 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001921 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001922
John McCallf85e1932011-06-15 23:02:42 +00001923 if (StripObjCLifetime)
1924 Quals.removeObjCLifetime();
1925
Mike Stump1eb44332009-09-09 15:08:12 +00001926 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001927 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001928 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001929 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001930 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001931
1932 // Build a pointer to ToPointee. It has the right qualifiers
1933 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001934 if (isa<ObjCObjectPointerType>(ToType))
1935 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001936 return Context.getPointerType(ToPointee);
1937 }
1938
1939 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001940 QualType QualifiedCanonToPointee
1941 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001942
Douglas Gregorda80f742010-12-01 21:43:58 +00001943 if (isa<ObjCObjectPointerType>(ToType))
1944 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1945 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001946}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001947
Mike Stump1eb44332009-09-09 15:08:12 +00001948static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-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 Gregor2ade35e2010-06-16 00:17:44 +00001954 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001955 return !InOverloadResolution;
1956
Douglas Gregorce940492009-09-25 04:25:58 +00001957 return Expr->isNullPointerConstant(Context,
1958 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1959 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001960}
Mike Stump1eb44332009-09-09 15:08:12 +00001961
Douglas Gregor8e9bebd2008-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 Gregor071f2ae2008-11-27 00:15:41 +00001968///
Douglas Gregor7ca09762008-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 Gregor45920e82008-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 Gregor8e9bebd2008-10-21 16:13:35 +00001978bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001979 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001980 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001981 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001982 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001983 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1984 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001985 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001986
Mike Stump1eb44332009-09-09 15:08:12 +00001987 // Conversion from a null pointer constant to any Objective-C pointer type.
1988 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001989 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001990 ConvertedType = ToType;
1991 return true;
1992 }
1993
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001994 // Blocks: Block pointers can be converted to void*.
1995 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001996 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-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 Stump1eb44332009-09-09 15:08:12 +00002002 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002003 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002004 ConvertedType = ToType;
2005 return true;
2006 }
2007
Sebastian Redl6e8ed162009-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 Stump1eb44332009-09-09 15:08:12 +00002010 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002011 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002012 ConvertedType = ToType;
2013 return true;
2014 }
2015
Ted Kremenek6217b802009-07-29 21:53:49 +00002016 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-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 Carlssonbbf306b2009-08-28 15:55:56 +00002021 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002022 ConvertedType = ToType;
2023 return true;
2024 }
Sebastian Redl07779722008-10-31 14:43:28 +00002025
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002026 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002027 // , including objective-c pointers.
2028 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002029 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002030 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002031 ConvertedType = BuildSimilarlyQualifiedPointerType(
2032 FromType->getAs<ObjCObjectPointerType>(),
2033 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002034 ToType, Context);
2035 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002036 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002037 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002038 if (!FromTypePtr)
2039 return false;
2040
2041 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002042
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002043 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-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 Gregor8e9bebd2008-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 Friedman13578692010-08-05 02:49:48 +00002051 if (FromPointeeType->isIncompleteOrObjectType() &&
2052 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002053 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002054 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002055 ToType, Context,
2056 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002057 return true;
2058 }
2059
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002060 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002061 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002062 ToPointeeType->isVoidType()) {
2063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2064 ToPointeeType,
2065 ToType, Context);
2066 return true;
2067 }
2068
Douglas Gregorf9201e02009-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 Blaikie4e4d0842012-03-11 07:00:24 +00002071 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002072 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002073 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002074 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002075 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002076 return true;
2077 }
2078
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002079 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002080 //
Douglas Gregorbc0805a2008-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 Gregor94b1dd22008-10-24 04:54:22 +00002090 // Note that we do not check for ambiguity or inaccessibility
2091 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002092 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002093 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002094 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002095 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002096 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002097 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002098 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002099 ToType, Context);
2100 return true;
2101 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002102
Fariborz Jahanian5da3c082011-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 Gregorc7887512008-12-19 19:13:09 +00002111 return false;
2112}
Douglas Gregor028ea4b2011-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 Gregorc7887512008-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 Stump1eb44332009-09-09 15:08:12 +00002131bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002132 QualType& ConvertedType,
2133 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002134 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002135 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002136
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002137 // The set of qualifiers on the type we're converting from.
2138 Qualifiers FromQualifiers = FromType.getQualifiers();
2139
Steve Naroff14108da2009-07-10 23:34:53 +00002140 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002141 const ObjCObjectPointerType* ToObjCPtr =
2142 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002143 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002144 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002145
Steve Naroff14108da2009-07-10 23:34:53 +00002146 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-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 Gregor028ea4b2011-04-26 23:16:46 +00002153 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002154 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002155 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002156 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002157 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002158 return true;
2159 }
2160 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002161 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002162 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002163 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002164 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002165 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-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 Jahanianee9ca692010-03-15 18:36:00 +00002171 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2172 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002173 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002174 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2175 FromObjCPtr->getPointeeType()))
2176 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002177 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002178 ToObjCPtr->getPointeeType(),
2179 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002180 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-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 Takumidfbb02a2011-01-27 07:10:08 +00002189 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002190 ToObjCPtr->getPointeeType(),
2191 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002192 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002193 return true;
2194 }
Mike Stump1eb44332009-09-09 15:08:12 +00002195 }
Steve Naroff14108da2009-07-10 23:34:53 +00002196 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002197 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002198 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002199 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002200 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002201 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002202 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002203 // to a block pointer type.
2204 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002205 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002206 return true;
2207 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002208 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002209 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002210 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002211 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002212 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002213 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002214 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002215 return true;
2216 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002217 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002218 return false;
2219
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002220 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002221 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002222 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002223 else if (const BlockPointerType *FromBlockPtr =
2224 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002225 FromPointeeType = FromBlockPtr->getPointeeType();
2226 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002227 return false;
2228
Douglas Gregorc7887512008-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 Gregorda80f742010-12-01 21:43:58 +00002236 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002237 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002238 return true;
2239 }
Fariborz Jahanian83b7b312010-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 McCallf85e1932011-06-15 23:02:42 +00002246
Douglas Gregorda80f742010-12-01 21:43:58 +00002247 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002248 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002249 return true;
2250 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002251
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002252 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-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 Stump1eb44332009-09-09 15:08:12 +00002256 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002257 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002258 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002259 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07002269 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregorc7887512008-12-19 19:13:09 +00002270 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2271 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2272 return false;
2273
2274 bool HasObjCConversion = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07002275 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2276 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregorc7887512008-12-19 19:13:09 +00002277 // Okay, the types match exactly. Nothing to do.
Stephen Hines651f13c2014-04-23 16:59:28 -07002278 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2279 ToFunctionType->getReturnType(),
Douglas Gregorc7887512008-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 Stump1eb44332009-09-09 15:08:12 +00002287
Douglas Gregorc7887512008-12-19 19:13:09 +00002288 // Check argument types.
Stephen Hines651f13c2014-04-23 16:59:28 -07002289 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregorc7887512008-12-19 19:13:09 +00002290 ArgIdx != NumArgs; ++ArgIdx) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002291 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2292 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregorc7887512008-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 Gregor028ea4b2011-04-26 23:16:46 +00002309 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002310 IncompatibleObjC = true;
2311 return true;
2312 }
2313 }
2314
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002315 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002316}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002317
John McCallf85e1932011-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 Blaikie4e4d0842012-03-11 07:00:24 +00002329 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-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 McCall200fa532012-02-08 00:46:36 +00002343 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-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 Jahaniane3c8c642011-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 Jahanian569bd8f2011-02-13 20:01:48 +00002409 if (!FromFunctionType || !ToFunctionType)
2410 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002411
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002412 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002413 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002414
2415 // Perform the quick checks that will tell us whether these
2416 // function types are obviously different.
Stephen Hines651f13c2014-04-23 16:59:28 -07002417 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian569bd8f2011-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;
Stephen Hines651f13c2014-04-23 16:59:28 -07002427 if (Context.hasSameType(FromFunctionType->getReturnType(),
2428 ToFunctionType->getReturnType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002429 // Okay, the types match exactly. Nothing to do.
2430 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07002431 QualType RHS = FromFunctionType->getReturnType();
2432 QualType LHS = ToFunctionType->getReturnType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002433 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07002450 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002451 ArgIdx != NumArgs; ++ArgIdx) {
2452 IncompatibleObjC = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07002453 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2454 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian569bd8f2011-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 Jahanian78213e42011-09-28 21:52:05 +00002466 if (LangOpts.ObjCAutoRefCount &&
2467 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2468 ToFunctionType))
2469 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002470
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002471 ConvertedType = ToType;
2472 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002473}
2474
Richard Trieu6efd4c52011-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 Trieua6dc7ef2011-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 Trieu6efd4c52011-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>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002499 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieu6efd4c52011-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 Trieu6efd4c52011-11-23 22:32:32 +00002506 }
2507
Richard Trieua6dc7ef2011-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 Trieu6efd4c52011-11-23 22:32:32 +00002514 FromType = FromType.getNonReferenceType();
2515 ToType = ToType.getNonReferenceType();
2516
Richard Trieu6efd4c52011-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 Trieua6dc7ef2011-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 Trieu6efd4c52011-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
Stephen Hines651f13c2014-04-23 16:59:28 -07002539 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2540 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2541 << FromFunction->getNumParams();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002542 return;
2543 }
2544
2545 // Handle different parameter types.
2546 unsigned ArgPos;
Stephen Hines651f13c2014-04-23 16:59:28 -07002547 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002548 PDiag << ft_parameter_mismatch << ArgPos + 1
Stephen Hines651f13c2014-04-23 16:59:28 -07002549 << ToFunction->getParamType(ArgPos)
2550 << FromFunction->getParamType(ArgPos);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002551 return;
2552 }
2553
2554 // Handle different return type.
Stephen Hines651f13c2014-04-23 16:59:28 -07002555 if (!Context.hasSameType(FromFunction->getReturnType(),
2556 ToFunction->getReturnType())) {
2557 PDiag << ft_return_type << ToFunction->getReturnType()
2558 << FromFunction->getReturnType();
Richard Trieu6efd4c52011-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
Stephen Hines651f13c2014-04-23 16:59:28 -07002573/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002574/// for equality of their argument types. Caller has already checked that
Eli Friedman06017002013-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07002577bool 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 Trieu7ea491c2013-08-09 21:42:32 +00002584 if (!Context.hasSameType(O->getUnqualifiedType(),
2585 N->getUnqualifiedType())) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002586 if (ArgPos)
2587 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo3151b7c2013-08-06 03:57:41 +00002588 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002589 }
2590 }
2591 return true;
2592}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002593
Douglas Gregor94b1dd22008-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 Redl9cc11e72009-07-25 15:41:38 +00002596/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-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 Carlsson61faec12009-09-12 04:46:44 +00002600bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002601 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002602 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002603 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002604 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002605 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002606
John McCalldaa8e4e2010-11-15 09:13:47 +00002607 Kind = CK_BitCast;
2608
David Blaikie50800fc2012-08-08 17:33:31 +00002609 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2610 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2611 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 McCall1d9b3b22011-09-09 05:25:32 +00002620 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2621 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002622 QualType FromPointeeType = FromPtrType->getPointeeType(),
2623 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002624
Douglas Gregor5fccd362010-03-03 23:55:11 +00002625 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2626 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002627 // We must have a derived-to-base conversion. Check an
2628 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002629 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2630 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002631 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002632 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002633 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002634
Anders Carlsson61faec12009-09-12 04:46:44 +00002635 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002636 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002637 }
2638 }
John McCall1d9b3b22011-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 Naroff14108da2009-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 Naroffde2e22d2009-07-15 18:40:39 +00002646 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002647 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002648 } else if (FromType->isBlockPointerType()) {
2649 Kind = CK_BlockPointerToObjCPointerCast;
2650 } else {
2651 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002652 }
John McCall1d9b3b22011-09-09 05:25:32 +00002653 } else if (ToType->isBlockPointerType()) {
2654 if (!FromType->isBlockPointerType())
2655 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002656 }
John McCalldaa8e4e2010-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 Gregor94b1dd22008-10-24 04:54:22 +00002663 return false;
2664}
2665
Sebastian Redl4433aaf2009-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 Takumidfbb02a2011-01-27 07:10:08 +00002672 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002673 bool InOverloadResolution,
2674 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002675 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-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 Gregorce940492009-09-25 04:25:58 +00002680 if (From->isNullPointerConstant(Context,
2681 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2682 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002683 ConvertedType = ToType;
2684 return true;
2685 }
2686
2687 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002688 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-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 Redl4433aaf2009-01-25 19:43:20 +00002696
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002697 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002698 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002699 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002700 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2701 ToClass.getTypePtr());
2702 return true;
2703 }
2704
2705 return false;
2706}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002707
Sebastian Redl4433aaf2009-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 McCall6b2accb2010-02-10 09:31:12 +00002710/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-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 Stump1eb44332009-09-09 15:08:12 +00002714bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002715 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002716 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002717 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002718 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002719 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002720 if (!FromPtrType) {
2721 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002722 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002723 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002724 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002725 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002726 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002727 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002728
Ted Kremenek6217b802009-07-29 21:53:49 +00002729 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002730 assert(ToPtrType && "No member pointer cast has a target type "
2731 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002732
Sebastian Redl21593ac2009-01-28 18:33:18 +00002733 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2734 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002735
Sebastian Redl21593ac2009-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 Redl4433aaf2009-01-25 19:43:20 +00002739
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002740 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002741 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-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 Redl4433aaf2009-01-25 19:43:20 +00002746
Sebastian Redl21593ac2009-01-28 18:33:18 +00002747 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2748 getUnqualifiedType())) {
Sebastian Redl21593ac2009-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 Redl4433aaf2009-01-25 19:43:20 +00002753 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002754
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002755 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-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 McCall6b2accb2010-02-10 09:31:12 +00002762 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002763 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2764 Paths.front(),
2765 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002766
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002767 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002768 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002769 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002770 return false;
2771}
2772
Douglas Gregor3940e3b2013-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 Gregor98cd5992008-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 McCallf85e1932011-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 Stump1eb44332009-09-09 15:08:12 +00002792bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002793Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002794 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002795 FromType = Context.getCanonicalType(FromType);
2796 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002797 ObjCLifetimeConversion = false;
2798
Douglas Gregor98cd5992008-10-21 23:43:52 +00002799 // If FromType and ToType are the same type, this is not a
2800 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002801 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002802 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002803
Douglas Gregor98cd5992008-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 Gregor98cd5992008-10-21 23:43:52 +00002808 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002809 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-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 Gregorf8268ae2008-10-22 17:49:05 +00002813 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002814 // until there are no more pointers or pointers-to-members left to
2815 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002816 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002817
Douglas Gregor621c92a2011-04-25 18:40:17 +00002818 Qualifiers FromQuals = FromType.getQualifiers();
2819 Qualifiers ToQuals = ToType.getQualifiers();
2820
John McCallf85e1932011-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 Gregor3940e3b2013-11-08 02:04:24 +00002826 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2827 ObjCLifetimeConversion = true;
John McCallf85e1932011-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 Gregor377e1bd2011-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 Gregor98cd5992008-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 Gregor621c92a2011-04-25 18:40:17 +00002846 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002847 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002848
Douglas Gregor98cd5992008-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 Gregor621c92a2011-04-25 18:40:17 +00002851 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002852 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002853 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002854
Douglas Gregor98cd5992008-10-21 23:43:52 +00002855 // Keep track of whether all prior cv-qualifiers in the "to" type
2856 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002857 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002858 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002859 }
Douglas Gregor98cd5992008-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 Gregora4923eb2009-11-16 21:35:15 +00002866 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002867}
2868
Douglas Gregorf7ecc302012-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 Gregor7d000652012-04-12 20:48:09 +00002874static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2875 bool InOverloadResolution,
2876 StandardConversionSequence &SCS,
2877 bool CStyle) {
Douglas Gregorf7ecc302012-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 Redlf78c0f92012-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>();
Stephen Hines651f13c2014-04-23 16:59:28 -07002902 if (CtorType->getNumParams() > 0) {
2903 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002904 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2905 return true;
2906 }
2907 return false;
2908}
2909
Sebastian Redl56a04282012-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 Blaikie3bc93e32012-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 Redl56a04282012-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).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002923 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl56a04282012-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 Redlf78c0f92012-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 Redl56a04282012-02-11 23:51:08 +00002940 if (ConstructorTmpl)
2941 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002942 /*ExplicitArgs*/ nullptr,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002943 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002944 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002945 else
2946 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002947 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002948 SuppressUserConversions);
Sebastian Redl56a04282012-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 Redl56a04282012-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 Gregor734d9862009-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 Gregor734d9862009-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 Gregor1ce55092013-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 McCall120d63c2010-08-24 20:38:10 +00002996static OverloadingResult
2997IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002998 UserDefinedConversionSequence &User,
2999 OverloadCandidateSet &CandidateSet,
Douglas Gregor1ce55092013-11-07 22:34:54 +00003000 bool AllowExplicit,
3001 bool AllowObjCConversionOnExplicit) {
Douglas Gregora1977bf2013-11-08 01:20:25 +00003002 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor1ce55092013-11-07 22:34:54 +00003003
Douglas Gregor3fbaf3e2010-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 Kremenek6217b802009-07-29 21:53:49 +00003009 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-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 McCall120d63c2010-08-24 20:38:10 +00003018 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003019 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003020 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003021 ConstructorsOnly = true;
3022
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003023 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-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 Gregor393896f2009-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 Redlcf15cef2011-12-22 18:58:38 +00003031
3032 Expr **Args = &From;
3033 unsigned NumArgs = 1;
3034 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003035 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramere5753592013-09-09 14:48:42 +00003036 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl56a04282012-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 Redlcf15cef2011-12-22 18:58:38 +00003046 Args = InitList->getInits();
3047 NumArgs = InitList->getNumInits();
3048 ListInitializing = true;
3049 }
3050
David Blaikie3bc93e32012-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 Gregorc1efaec2009-02-28 01:32:25 +00003053 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003054 NamedDecl *D = *Con;
3055 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3056
Douglas Gregordec06662009-08-21 18:42:58 +00003057 // Find the constructor (which may be a template).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003058 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregordec06662009-08-21 18:42:58 +00003059 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003060 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003061 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003062 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003063 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3064 else
John McCall9aa472c2010-03-19 07:35:19 +00003065 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003066
Sebastian Redlcf15cef2011-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 Redl1cd89c42012-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 Redlf78c0f92012-03-27 18:33:03 +00003079 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3080 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003081 }
3082 }
Douglas Gregordec06662009-08-21 18:42:58 +00003083 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003084 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003085 /*ExplicitArgs*/ nullptr,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003086 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003087 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003088 else
Fariborz Jahanian249cead2009-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 McCall120d63c2010-08-24 20:38:10 +00003091 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003092 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003093 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003094 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003095 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003096 }
3097 }
3098
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003099 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003100 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003101 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003102 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003103 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003104 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003105 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003106 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3107 // Add all of the conversion functions as candidates.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003108 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3109 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003110 DeclAccessPair FoundDecl = I.getPair();
3111 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-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 Jahanian8664ad52009-09-11 18:46:22 +00003116 CXXConversionDecl *Conv;
3117 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003118 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3119 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003120 else
John McCall32daa422010-03-31 01:36:47 +00003121 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003122
3123 if (AllowExplicit || !Conv->isExplicit()) {
3124 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003125 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3126 ActingContext, From, ToType,
Douglas Gregor1ce55092013-11-07 22:34:54 +00003127 CandidateSet,
3128 AllowObjCConversionOnExplicit);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003129 else
John McCall120d63c2010-08-24 20:38:10 +00003130 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor1ce55092013-11-07 22:34:54 +00003131 From, ToType, CandidateSet,
3132 AllowObjCConversionOnExplicit);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003133 }
3134 }
3135 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003136 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003137
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003138 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3139
Douglas Gregor60d62c22008-10-31 16:23:19 +00003140 OverloadCandidateSet::iterator Best;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003141 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3142 Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003143 case OR_Success:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003144 case OR_Deleted:
John McCall120d63c2010-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 Redlcf15cef2011-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 Gregor60d62c22008-10-31 16:23:19 +00003165 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003166 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003167 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003168 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003169 User.After.setAsIdentityConversion();
3170 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3171 User.After.setAllToTypes(ToType);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003172 return Result;
David Blaikie7530c032012-01-17 06:56:22 +00003173 }
3174 if (CXXConversionDecl *Conversion
John McCall120d63c2010-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 Bagnara7cc58b42011-10-05 07:56:41 +00003183 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003184 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003185 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003186 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003187
John McCall120d63c2010-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;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003198 return Result;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003199 }
David Blaikie7530c032012-01-17 06:56:22 +00003200 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003201
John McCall120d63c2010-08-24 20:38:10 +00003202 case OR_No_Viable_Function:
3203 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003204
John McCall120d63c2010-08-24 20:38:10 +00003205 case OR_Ambiguous:
3206 return OR_Ambiguous;
3207 }
3208
David Blaikie7530c032012-01-17 06:56:22 +00003209 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003210}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003211
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003212bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003213Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003214 ImplicitConversionSequence ICS;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003215 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3216 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003217 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003218 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor1ce55092013-11-07 22:34:54 +00003219 CandidateSet, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003220 if (OvResult == OR_Ambiguous)
Stephen Hines651f13c2014-04-23 16:59:28 -07003221 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3222 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo7419d012013-06-27 01:50:25 +00003223 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo288f76a2013-06-27 03:36:30 +00003224 if (!RequireCompleteType(From->getLocStart(), ToType,
Stephen Hines651f13c2014-04-23 16:59:28 -07003225 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo7419d012013-06-27 01:50:25 +00003226 From->getType(), From->getSourceRange()))
Stephen Hines651f13c2014-04-23 16:59:28 -07003227 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3228 << From->getType() << From->getSourceRange() << ToType;
3229 } else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003230 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003231 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003232 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003233}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003234
Douglas Gregorb734e242012-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
Stephen Hines651f13c2014-04-23 16:59:28 -07003239compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregorb734e242012-02-22 17:32:19 +00003240 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003241 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003242 return ImplicitConversionSequence::Indistinguishable;
Stephen Hines651f13c2014-04-23 16:59:28 -07003243
Douglas Gregorb734e242012-02-22 17:32:19 +00003244 // Objective-C++:
3245 // If both conversion functions are implicitly-declared conversions from
Stephen Hines651f13c2014-04-23 16:59:28 -07003246 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregorb734e242012-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07003250 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregorb734e242012-02-22 17:32:19 +00003251 if (!Conv1)
3252 return ImplicitConversionSequence::Indistinguishable;
Stephen Hines651f13c2014-04-23 16:59:28 -07003253
Douglas Gregorb734e242012-02-22 17:32:19 +00003254 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3255 if (!Conv2)
3256 return ImplicitConversionSequence::Indistinguishable;
Stephen Hines651f13c2014-04-23 16:59:28 -07003257
Douglas Gregorb734e242012-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)
Stephen Hines651f13c2014-04-23 16:59:28 -07003262 return Block1 ? ImplicitConversionSequence::Worse
3263 : ImplicitConversionSequence::Better;
Douglas Gregorb734e242012-02-22 17:32:19 +00003264 }
3265
3266 return ImplicitConversionSequence::Indistinguishable;
3267}
Stephen Hines651f13c2014-04-23 16:59:28 -07003268
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 Gregor8e9bebd2008-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 McCall120d63c2010-08-24 20:38:10 +00003279static ImplicitConversionSequence::CompareKind
3280CompareImplicitConversionSequences(Sema &S,
3281 const ImplicitConversionSequence& ICS1,
3282 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +00003292 //
John McCall1d318332010-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07003298
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 Gregor3fbaf3e2010-04-17 22:01:05 +00003324 if (ICS1.getKindRank() < ICS2.getKindRank())
3325 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003326 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003327 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003328
Benjamin Kramerb6eee072010-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 Redlcc7a6482011-11-01 15:53:09 +00003334 ImplicitConversionSequence::CompareKind Result =
3335 ImplicitConversionSequence::Indistinguishable;
3336
Douglas Gregor8e9bebd2008-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):
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003340
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,
3345 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3346 // 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 McCall1d318332010-01-12 00:44:57 +00003357 if (ICS1.isStandard())
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003358 // Standard conversion sequence S1 is a better conversion sequence than
3359 // standard conversion sequence S2 if [...]
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003360 Result = CompareStandardConversionSequences(S,
3361 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003362 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +00003369 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003370 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003371 Result = CompareStandardConversionSequences(S,
3372 ICS1.UserDefined.After,
3373 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003374 else
3375 Result = compareConversionFunctions(S,
3376 ICS1.UserDefined.ConversionFunction,
3377 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003378 }
3379
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003380 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003381}
3382
Douglas Gregor5a57efd2010-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 Takumidfbb02a2011-01-27 07:10:08 +00003387 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003388 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003389
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003390 return Context.hasSameUnqualifiedType(T1, T2);
3391}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003392
Douglas Gregorad323a82010-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 Takumidfbb02a2011-01-27 07:10:08 +00003402 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003403 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-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 Takumidfbb02a2011-01-27 07:10:08 +00003408
Douglas Gregorad323a82010-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 Gregor5a57efd2010-06-09 03:53:18 +00003416 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-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 Takumidfbb02a2011-01-27 07:10:08 +00003433
Douglas Gregorad323a82010-01-27 03:51:04 +00003434 return ImplicitConversionSequence::Indistinguishable;
3435}
3436
Douglas Gregor440a4832011-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.
Stephen Hines176edba2014-12-01 14:53:08 -08003439static bool
3440isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3441 const StandardConversionSequence &SCS2) {
Douglas Gregor440a4832011-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 Takumidfbb02a2011-01-27 07:10:08 +00003445 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003446 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003447 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-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 Gregorfcab48b2011-01-26 19:41:18 +00003455 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3456 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3457 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003458
Douglas Gregor440a4832011-01-26 14:52:12 +00003459 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3460 SCS2.IsLvalueReference) ||
3461 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Stephen Hines176edba2014-12-01 14:53:08 -08003462 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregor440a4832011-01-26 14:52:12 +00003463}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003464
Douglas Gregor8e9bebd2008-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 McCall120d63c2010-08-24 20:38:10 +00003468static ImplicitConversionSequence::CompareKind
3469CompareStandardConversionSequences(Sema &S,
3470 const StandardConversionSequence& SCS1,
3471 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-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 Gregorad323a82010-01-27 03:51:04 +00003481 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003482 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003483 return CK;
Douglas Gregor8e9bebd2008-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 Gregor8e9bebd2008-10-21 16:13:35 +00003493
Douglas Gregor57373262008-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 Stump1eb44332009-09-09 15:08:12 +00003497
Douglas Gregor57373262008-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 Gregorbc0805a2008-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 Gregorf70bdb92008-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 Stump1eb44332009-09-09 15:08:12 +00003512 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003513 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003514 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003515 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-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 Gregorbc0805a2008-10-23 00:40:37 +00003519 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3520 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-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 Gregorbc0805a2008-10-23 00:40:37 +00003524 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003525 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003526 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003527 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3528 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-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 McCall1d318332010-01-12 00:44:57 +00003532 QualType FromType1 = SCS1.getFromType();
3533 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-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 McCall120d63c2010-08-24 20:38:10 +00003538 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003539 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003540 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003541
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003542 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3543 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003544
John McCall120d63c2010-08-24 20:38:10 +00003545 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003546 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003547 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-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 Gregor0f7b3dc2011-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 Gregor01919692009-12-13 21:37:05 +00003565 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003566 }
Douglas Gregor57373262008-10-22 14:17:15 +00003567
3568 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3569 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003570 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003571 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003572 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003573
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003574 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-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 Takumidfbb02a2011-01-27 07:10:08 +00003580
Sebastian Redlf2e21e52009-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 Gregorad323a82010-01-27 03:51:04 +00003587 QualType T1 = SCS1.getToType(2);
3588 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003589 T1 = S.Context.getCanonicalType(T1);
3590 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003591 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003592 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3593 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003594 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-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 Carruth6df868e2010-12-12 08:17:55 +00003604 // If the type is an array type, promote the element qualifiers to the
3605 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003606 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003607 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003608 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003609 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003610 if (T2.isMoreQualifiedThan(T1))
3611 return ImplicitConversionSequence::Better;
3612 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003613 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003614 }
3615 }
Douglas Gregor57373262008-10-22 14:17:15 +00003616
Francois Pichet1c98d622011-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07003629 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3630 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003631 S.Context.getTypeSize(SCS1.getFromType()) ==
Stephen Hines651f13c2014-04-23 16:59:28 -07003632 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet1c98d622011-09-18 21:37:37 +00003633 return ImplicitConversionSequence::Better;
3634
Douglas Gregor57373262008-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 Stump1eb44332009-09-09 15:08:12 +00003640/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Stephen Hines176edba2014-12-01 14:53:08 -08003641static ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003642CompareQualificationConversions(Sema &S,
3643 const StandardConversionSequence& SCS1,
3644 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003645 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-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 Gregorad323a82010-01-27 03:51:04 +00003657 QualType T1 = SCS1.getToType(2);
3658 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003659 T1 = S.Context.getCanonicalType(T1);
3660 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003661 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003662 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3663 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003664
3665 // If the types are the same, we won't learn anything by unwrapped
3666 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003667 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003668 return ImplicitConversionSequence::Indistinguishable;
3669
Chandler Carruth28e318c2009-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 McCall120d63c2010-08-24 20:38:10 +00003673 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003674 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003675 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003676
Mike Stump1eb44332009-09-09 15:08:12 +00003677 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003678 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-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 McCall120d63c2010-08-24 20:38:10 +00003690 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-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 Gregorf8268ae2008-10-22 17:49:05 +00003694 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-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 Stump1eb44332009-09-09 15:08:12 +00003709
Douglas Gregor57373262008-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 Stump1eb44332009-09-09 15:08:12 +00003717
Douglas Gregor57373262008-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 McCall120d63c2010-08-24 20:38:10 +00003725 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003726 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003727 }
3728
Douglas Gregor57373262008-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 Gregora9bff302010-02-28 18:30:25 +00003733 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003734 Result = ImplicitConversionSequence::Indistinguishable;
3735 break;
3736
3737 case ImplicitConversionSequence::Indistinguishable:
3738 break;
3739
3740 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003741 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003742 Result = ImplicitConversionSequence::Indistinguishable;
3743 break;
3744 }
3745
3746 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003747}
3748
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003749/// CompareDerivedToBaseConversions - Compares two standard conversion
3750/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-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.
Stephen Hines176edba2014-12-01 14:53:08 -08003754static ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003755CompareDerivedToBaseConversions(Sema &S,
3756 const StandardConversionSequence& SCS1,
3757 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003758 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003759 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003760 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003761 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-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 McCall120d63c2010-08-24 20:38:10 +00003766 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003767 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003768 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003769
3770 // Canonicalize all of the types.
John McCall120d63c2010-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 Gregorbc0805a2008-10-23 00:40:37 +00003775
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003776 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-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 Gregorcb7de522008-11-26 23:31:11 +00003780 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003781 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003782 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-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 Stump1eb44332009-09-09 15:08:12 +00003787 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003788 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003789 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003790 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003791 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003792 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003793 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003794 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003795
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003796 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003797 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003798 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003799 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003800 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003801 return ImplicitConversionSequence::Worse;
3802 }
Douglas Gregorf70bdb92008-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 McCall120d63c2010-08-24 20:38:10 +00003806 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003807 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003808 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003809 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-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 Stump1eb44332009-09-09 15:08:12 +00003867
Douglas Gregor395cc372011-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 Gregorf70bdb92008-10-29 14:50:44 +00003880 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003881 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003882
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003883 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-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 Takumidfbb02a2011-01-27 07:10:08 +00003887 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003888 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003889 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003890 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003891 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003892 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003893 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-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 Jahanian2357da02009-10-20 20:07:35 +00003903 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003904 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003905 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003906 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003907 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-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 McCall120d63c2010-08-24 20:38:10 +00003912 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003913 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003914 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003915 return ImplicitConversionSequence::Worse;
3916 }
3917 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003918
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003919 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003920 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-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 McCall120d63c2010-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 Gregor225c41e2008-11-03 19:09:14 +00003927 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003928 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003929 return ImplicitConversionSequence::Worse;
3930 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003931
Douglas Gregor225c41e2008-11-03 19:09:14 +00003932 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-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 McCall120d63c2010-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 Gregor225c41e2008-11-03 19:09:14 +00003939 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003940 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003941 return ImplicitConversionSequence::Worse;
3942 }
3943 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003944
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003945 return ImplicitConversionSequence::Indistinguishable;
3946}
3947
Douglas Gregor0162c1c2013-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 Gregorabe183d2010-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 Gregor569c3162010-08-07 11:51:51 +00003967 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003968 bool &ObjCConversion,
3969 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-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 Gregor569c3162010-08-07 11:51:51 +00003984 DerivedToBase = false;
3985 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003986 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003987 if (UnqualT1 == UnqualT2) {
3988 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003989 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003990 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3991 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003992 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003993 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3994 UnqualT2->isObjCObjectOrInterfaceType() &&
3995 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3996 ObjCConversion = true;
Douglas Gregorabe183d2010-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 Gregora6ce3e62011-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 McCallf85e1932011-06-15 23:02:42 +00004022 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4023 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregor3940e3b2013-11-08 02:04:24 +00004024 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4025 ObjCLifetimeConversion = true;
4026
John McCallf85e1932011-06-15 23:02:42 +00004027 T1Quals.removeObjCLifetime();
4028 T2Quals.removeObjCLifetime();
John McCallf85e1932011-06-15 23:02:42 +00004029 }
4030
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004031 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00004032 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00004033 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004034 return Ref_Compatible_With_Added_Qualification;
4035 else
4036 return Ref_Related;
4037}
4038
Douglas Gregor604eb652010-08-11 02:15:33 +00004039/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00004040/// with DeclType. Return true if something definite is found.
4041static bool
Douglas Gregor604eb652010-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 Redl4680bf22010-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
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004050 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004051 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4052 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redl4680bf22010-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 Takumidfbb02a2011-01-27 07:10:08 +00004066 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004067 // explicit conversions, skip it.
4068 if (!AllowExplicit && Conv->isExplicit())
4069 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004070
Douglas Gregor604eb652010-08-11 02:15:33 +00004071 if (AllowRvalues) {
4072 bool DerivedToBase = false;
4073 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004074 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-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 Gregor604eb652010-08-11 02:15:33 +00004085 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004086 S.CompareReferenceRelationship(
4087 DeclLoc,
4088 Conv->getConversionType().getNonReferenceType()
4089 .getUnqualifiedType(),
4090 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004091 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004092 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-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 Redl4680bf22010-06-30 18:13:39 +00004105 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004106
Douglas Gregor604eb652010-08-11 02:15:33 +00004107 if (ConvTemplate)
4108 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor1ce55092013-11-07 22:34:54 +00004109 Init, DeclType, CandidateSet,
4110 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor604eb652010-08-11 02:15:33 +00004111 else
4112 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor1ce55092013-11-07 22:34:54 +00004113 DeclType, CandidateSet,
4114 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004115 }
4116
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004117 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4118
Sebastian Redl4680bf22010-06-30 18:13:39 +00004119 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004120 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-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 Bagnara7cc58b42011-10-05 07:56:41 +00004138 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004139 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004140 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-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 Takumidfbb02a2011-01-27 07:10:08 +00004161
David Blaikie7530c032012-01-17 06:56:22 +00004162 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004163}
4164
Douglas Gregorabe183d2010-04-13 16:31:36 +00004165/// \brief Compute an implicit conversion sequence for reference
4166/// initialization.
4167static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004168TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004169 SourceLocation DeclLoc,
4170 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004171 bool AllowExplicit) {
Douglas Gregorabe183d2010-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 Gregor569c3162010-08-07 11:51:51 +00004194 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004195 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004196 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004197 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004198 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004199 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004200
Douglas Gregorabe183d2010-04-13 16:31:36 +00004201
Sebastian Redl4680bf22010-06-30 18:13:39 +00004202 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-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 Redl4680bf22010-06-30 18:13:39 +00004206 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004207 if (!isRValRef) {
Sebastian Redl4680bf22010-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 Gregorabe183d2010-04-13 16:31:36 +00004214 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-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 Gregor569c3162010-08-07 11:51:51 +00004223 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4224 : ObjCConversion? ICK_Compatible_Conversion
4225 : ICK_Identity;
Sebastian Redl4680bf22010-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 Gregor440a4832011-01-26 14:52:12 +00004233 ICS.Standard.IsLvalueReference = !isRValRef;
4234 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4235 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004236 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004237 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004238 ICS.Standard.CopyConstructor = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004239 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004240
Sebastian Redl4680bf22010-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 Gregorabe183d2010-04-13 16:31:36 +00004245 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004246 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004247
Sebastian Redl4680bf22010-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 Takumidfbb02a2011-01-27 07:10:08 +00004256 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004257 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004258 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4259 Init, T2, /*AllowRvalues=*/false,
4260 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004261 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004262 }
4263 }
4264
Sebastian Redl4680bf22010-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 Gregor8dde14e2011-01-24 16:14:37 +00004267 // shall be an rvalue reference.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004268 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004269 return ICS;
4270
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004271 // -- If the initializer expression
4272 //
4273 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004274 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-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 Takumidfbb02a2011-01-27 07:10:08 +00004281 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-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 Takumidfbb02a2011-01-27 07:10:08 +00004295 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004296 S.getLangOpts().CPlusPlus11 ||
Stephen Hines176edba2014-12-01 14:53:08 -08004297 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004298 ICS.Standard.IsLvalueReference = !isRValRef;
4299 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004300 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004301 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004302 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004303 ICS.Standard.CopyConstructor = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004304 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004305 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004306 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004307
Douglas Gregor8dde14e2011-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 Takumidfbb02a2011-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 Gregor8dde14e2011-01-24 16:14:37 +00004312 // "cv3 T3",
4313 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004314 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004315 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004316 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004317 // class subobject).
4318 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004319 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-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 Takumidfbb02a2011-01-27 07:10:08 +00004327 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004328 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4329 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4330
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004331 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004332 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004333
Stephen Hines176edba2014-12-01 14:53:08 -08004334 // A temporary of function type cannot be created; don't even try.
4335 if (T1->isFunctionType())
4336 return ICS;
4337
Douglas Gregorabe183d2010-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 McCallf85e1932011-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 Gregorabe183d2010-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 Gregor2ad746a2011-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 Gregorabe183d2010-04-13 16:31:36 +00004378 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-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 McCall120d63c2010-08-24 20:38:10 +00004388 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4389 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004390 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004391 /*CStyle=*/false,
Douglas Gregor1ce55092013-11-07 22:34:54 +00004392 /*AllowObjCWritebackConversion=*/false,
4393 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorabe183d2010-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 Gregor440a4832011-01-26 14:52:12 +00004398 ICS.Standard.IsLvalueReference = !isRValRef;
Stephen Hines176edba2014-12-01 14:53:08 -08004399 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregor440a4832011-01-26 14:52:12 +00004400 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004401 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004402 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004403 } else if (ICS.isUserDefined()) {
Stephen Hines176edba2014-12-01 14:53:08 -08004404 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 Gregor203050c2011-10-04 23:59:32 +00004420 }
Stephen Hines176edba2014-12-01 14:53:08 -08004421
Stephen Hines651f13c2014-04-23 16:59:28 -07004422 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregorabe183d2010-04-13 16:31:36 +00004423 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004424 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Stephen Hines176edba2014-12-01 14:53:08 -08004425 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4426 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004427 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4428 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004429 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004430
Douglas Gregorabe183d2010-04-13 16:31:36 +00004431 return ICS;
4432}
4433
Sebastian Redl5405b812011-10-16 18:19:34 +00004434static ImplicitConversionSequence
4435TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4436 bool SuppressUserConversions,
4437 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004438 bool AllowObjCWritebackConversion,
4439 bool AllowExplicit = false);
Sebastian Redl5405b812011-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 Redlb832f6d2012-01-23 22:09:39 +00004455 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004456 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004457 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004458 return Result;
4459
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004460 // 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 }
4480 // FIXME: Check the other conditions here: array of character type,
4481 // initializer is a string literal.
4482 if (ToType->isArrayType()) {
4483 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 Redl5405b812011-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.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004502 //
4503 // C++14 [over.ics.list]p3:
4504 // Otherwise, if the parameter type is "array of N X", if the initializer
4505 // list has exactly N elements or if it has fewer than N elements and X is
4506 // default-constructible, and if all the elements of the initializer list
4507 // can be implicitly converted to X, the implicit conversion sequence is
4508 // the worst conversion necessary to convert an element of the list to X.
4509 //
4510 // FIXME: We're missing a lot of these checks.
Sebastian Redladfb5352012-02-27 22:38:26 +00004511 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004512 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004513 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004514 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004515 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004516 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-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 Gregor5b4bf132012-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 Redladfb5352012-02-27 22:38:26 +00004545 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004546 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004547 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004548
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004549 // C++14 [over.ics.list]p4:
Sebastian Redl5405b812011-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 Redlcf15cef2011-12-22 18:58:38 +00004556 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4557 // This function can deal with initializer lists.
Richard Smith798186a2013-09-06 22:30:28 +00004558 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4559 /*AllowExplicit=*/false,
4560 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor1ce55092013-11-07 22:34:54 +00004561 AllowObjCWritebackConversion,
4562 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004563 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004564
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004565 // C++14 [over.ics.list]p5:
Sebastian Redl5405b812011-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 Redl5405b812011-10-16 18:19:34 +00004570 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-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);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004577 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redlcc7a6482011-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);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004587 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004588 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004589 return Result;
4590 }
4591
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004592 // C++14 [over.ics.list]p6:
Sebastian Redl5405b812011-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 Redl1cdb70b2011-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 Smith3082be22013-09-06 01:22:42 +00004627 if (RefRelationship >= Sema::Ref_Related) {
Richard Smith798186a2013-09-06 22:30:28 +00004628 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4629 SuppressUserConversions,
4630 /*AllowExplicit=*/false);
Richard Smith3082be22013-09-06 01:22:42 +00004631 }
Sebastian Redl1cdb70b2011-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 Redl5405b812011-10-16 18:19:34 +00004658 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004659 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004660
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004661 // C++14 [over.ics.list]p7:
Sebastian Redl5405b812011-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()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004665 // - 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 Redl5405b812011-10-16 18:19:34 +00004668 unsigned NumInits = From->getNumInits();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004669 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redl5405b812011-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 McCalle14ba2c2012-04-04 02:40:27 +00004679 Result.Standard.setFromType(ToType);
4680 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004681 }
4682 return Result;
4683 }
4684
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004685 // C++14 [over.ics.list]p8:
Sebastian Redl5405b812011-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 Gregor27c8dc02008-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 Gregor225c41e2008-11-03 19:09:14 +00004695/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004696/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004697static ImplicitConversionSequence
4698TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004699 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004700 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004701 bool AllowObjCWritebackConversion,
4702 bool AllowExplicit) {
Sebastian Redl5405b812011-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 Gregorabe183d2010-04-13 16:31:36 +00004707 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004708 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004709 /*FIXME:*/From->getLocStart(),
4710 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004711 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004712
John McCall120d63c2010-08-24 20:38:10 +00004713 return TryImplicitConversion(S, From, ToType,
4714 SuppressUserConversions,
4715 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004716 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004717 /*CStyle=*/false,
Douglas Gregor1ce55092013-11-07 22:34:54 +00004718 AllowObjCWritebackConversion,
4719 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004720}
4721
Anna Zaksf3546ee2011-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 Gregor96176b32008-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 McCall120d63c2010-08-24 20:38:10 +00004737static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004738TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004739 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004740 CXXMethodDecl *Method,
4741 CXXRecordDecl *ActingContext) {
4742 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-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 McCall120d63c2010-08-24 20:38:10 +00004747 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-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 Gregor96176b32008-11-18 23:14:02 +00004752
4753 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004754 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004755 FromType = PT->getPointeeType();
4756
Douglas Gregor2c9a03f2011-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 Carlssona552f7c2009-05-01 18:34:30 +00004762 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004763
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004764 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004765 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004766 // parameter is
4767 //
NAKAMURA Takumi00995302011-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 Gregor2c9a03f2011-01-26 19:30:28 +00004771 // ref-qualifier
4772 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004773 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004774 // cv-qualification on the member function declaration.
4775 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004776 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004777 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-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 Gregor2c9a03f2011-01-26 19:30:28 +00004782 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004783 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004784 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004785 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004786 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004787 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004788 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004789 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004790 }
Douglas Gregor96176b32008-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 McCall120d63c2010-08-24 20:38:10 +00004794 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004795 ImplicitConversionKind SecondKind;
4796 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4797 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004798 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004799 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004800 else {
John McCallb1bdc622010-02-25 01:37:24 +00004801 ICS.setBad(BadConversionSequence::unrelated_class,
4802 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004803 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004804 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004805
Douglas Gregor2c9a03f2011-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 Takumidfbb02a2011-01-27 07:10:08 +00004811
Douglas Gregor2c9a03f2011-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 Takumidfbb02a2011-01-27 07:10:08 +00004815 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-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 Takumidfbb02a2011-01-27 07:10:08 +00004824 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004825 ImplicitParamType);
4826 return ICS;
4827 }
4828 break;
4829 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004830
Douglas Gregor96176b32008-11-18 23:14:02 +00004831 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004832 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004833 ICS.Standard.setAsIdentityConversion();
4834 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004835 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004836 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004837 ICS.Standard.ReferenceBinding = true;
4838 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004839 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004840 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004841 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4842 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4843 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-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 Wiegley429bb272011-04-08 18:41:53 +00004850ExprResult
4851Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004852 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004853 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004854 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004855 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004856 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004857 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004858
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004859 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004860 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004861 FromRecordType = PT->getPointeeType();
4862 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004863 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004864 } else {
4865 FromRecordType = From->getType();
4866 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004867 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004868 }
4869
John McCall701c89e2009-12-03 04:06:58 +00004870 // Note that we always use the true parent context when performing
4871 // the actual argument initialization.
Stephen Hines176edba2014-12-01 14:53:08 -08004872 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4873 *this, From->getType(), FromClassification, Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-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 Dunbar96a00142012-03-09 18:35:03 +00004880 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-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 Wiegley429bb272011-04-08 18:41:53 +00004886 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004887 }
4888 }
4889
Daniel Dunbar96a00142012-03-09 18:35:03 +00004890 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004891 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004892 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004893 }
Mike Stump1eb44332009-09-09 15:08:12 +00004894
John Wiegley429bb272011-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();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004900 From = FromRes.get();
John Wiegley429bb272011-04-08 18:41:53 +00004901 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004902
Douglas Gregor5fccd362010-03-03 23:55:11 +00004903 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004904 From = ImpCastExprToType(From, DestType, CK_NoOp,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004905 From->getValueKind()).get();
4906 return From;
Douglas Gregor96176b32008-11-18 23:14:02 +00004907}
4908
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004909/// TryContextuallyConvertToBool - Attempt to contextually convert the
4910/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004911static ImplicitConversionSequence
4912TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall120d63c2010-08-24 20:38:10 +00004913 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004914 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004915 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004916 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004917 /*CStyle=*/false,
Douglas Gregor1ce55092013-11-07 22:34:54 +00004918 /*AllowObjCWritebackConversion=*/false,
4919 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor09f41cf2009-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 Wiegley429bb272011-04-08 18:41:53 +00004924ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004925 if (checkPlaceholderForOverload(*this, From))
4926 return ExprError();
4927
John McCall120d63c2010-08-24 20:38:10 +00004928 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004929 if (!ICS.isBad())
4930 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004931
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004932 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004933 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004934 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004935 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004936 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004937}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004938
Richard Smith8ef7b202012-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:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004949 case ICK_NoReturn_Adjustment:
Richard Smith8ef7b202012-01-18 23:55:52 +00004950 case ICK_Integral_Promotion:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004951 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smith8ef7b202012-01-18 23:55:52 +00004952 return true;
4953
4954 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004955 // Conversion from an integral or unscoped enumeration type to bool is
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004956 // 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 Smith2bcb9842012-09-13 22:00:12 +00004962 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4963 SCS.getToType(2)->isBooleanType();
4964
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004965 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 Smith8ef7b202012-01-18 23:55:52 +00004975 case ICK_Floating_Integral:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004976 case ICK_Compatible_Conversion:
4977 case ICK_Derived_To_Base:
4978 case ICK_Vector_Conversion:
4979 case ICK_Vector_Splat:
Richard Smith8ef7b202012-01-18 23:55:52 +00004980 case ICK_Complex_Real:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004981 case ICK_Block_Pointer_Conversion:
4982 case ICK_TransparentUnionConversion:
4983 case ICK_Writeback_Conversion:
4984 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-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:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004990 llvm_unreachable("found a first conversion kind in Second");
4991
Richard Smith8ef7b202012-01-18 23:55:52 +00004992 case ICK_Qualification:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004993 llvm_unreachable("found a third conversion kind in Second");
Richard Smith8ef7b202012-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.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005005static 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 Smith8ef7b202012-01-18 23:55:52 +00005011
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005012 if (checkPlaceholderForOverload(S, From))
Richard Smith8ef7b202012-01-18 23:55:52 +00005013 return ExprError();
5014
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005015 // 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 Smith8ef7b202012-01-18 23:55:52 +00005020 ImplicitConversionSequence ICS =
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005021 TryCopyInitialization(S, From, T,
Richard Smith8ef7b202012-01-18 23:55:52 +00005022 /*SuppressUserConversions=*/false,
Richard Smith8ef7b202012-01-18 23:55:52 +00005023 /*InOverloadResolution=*/false,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005024 /*AllowObjcWritebackConversion=*/false,
5025 /*AllowExplicit=*/false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005026 StandardConversionSequence *SCS = nullptr;
Richard Smith8ef7b202012-01-18 23:55:52 +00005027 switch (ICS.getKind()) {
5028 case ImplicitConversionSequence::StandardConversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00005029 SCS = &ICS.Standard;
5030 break;
5031 case ImplicitConversionSequence::UserDefinedConversion:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005032 // We are converting to a non-class type, so the Before sequence
5033 // must be trivial.
Richard Smith8ef7b202012-01-18 23:55:52 +00005034 SCS = &ICS.UserDefined.After;
5035 break;
5036 case ImplicitConversionSequence::AmbiguousConversion:
5037 case ImplicitConversionSequence::BadConversion:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005038 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 Smith8ef7b202012-01-18 23:55:52 +00005042 return ExprError();
5043
5044 case ImplicitConversionSequence::EllipsisConversion:
5045 llvm_unreachable("ellipsis conversion in converted constant expression");
5046 }
5047
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005048 // 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 Smith8ef7b202012-01-18 23:55:52 +00005063 if (Result.isInvalid())
5064 return Result;
5065
5066 // Check for a narrowing implicit conversion.
5067 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00005068 QualType PreNarrowingType;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005069 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smithf6028062012-03-23 23:55:39 +00005070 PreNarrowingType)) {
Richard Smith8ef7b202012-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:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005078 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00005079 << CCE << /*Constant*/1
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005080 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00005081 break;
5082
5083 case NK_Type_Narrowing:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005084 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smith8ef7b202012-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 Gribenkocfa88f82013-01-12 19:30:44 +00005090 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00005091 Expr::EvalResult Eval;
5092 Eval.Diag = &Notes;
5093
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005094 if ((T->isReferenceType()
5095 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5096 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5097 (RequireInt && !Eval.Val.isInt())) {
Richard Smith8ef7b202012-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 Smithf72fccf2012-01-30 22:27:01 +00005101 } else {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005102 Value = Eval.Val;
Richard Smithf72fccf2012-01-30 22:27:01 +00005103
5104 if (Notes.empty()) {
5105 // It's a constant expression.
5106 return Result;
5107 }
Richard Smith8ef7b202012-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)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005113 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smith8ef7b202012-01-18 23:55:52 +00005114 else {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005115 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005116 << CCE << From->getSourceRange();
5117 for (unsigned I = 0; I < Notes.size(); ++I)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005118 S.Diag(Notes[I].first, Notes[I].second);
Richard Smith8ef7b202012-01-18 23:55:52 +00005119 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005120 return ExprError();
Richard Smith8ef7b202012-01-18 23:55:52 +00005121}
5122
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005123ExprResult 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 McCall0bcc9bc2011-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 Jahanian79d3f042010-05-12 23:29:11 +00005150}
John McCall120d63c2010-08-24 20:38:10 +00005151
John McCall0bcc9bc2011-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 Gregor1ce55092013-11-07 22:34:54 +00005165 /*AllowObjCWritebackConversion=*/false,
5166 /*AllowObjCConversionOnExplicit=*/true);
John McCall0bcc9bc2011-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 McCall3c3b7f92011-10-25 17:37:35 +00005190 if (checkPlaceholderForOverload(*this, From))
5191 return ExprError();
5192
John McCallc12c5bb2010-05-15 11:32:37 +00005193 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005194 ImplicitConversionSequence ICS =
5195 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005196 if (!ICS.isBad())
5197 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005198 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005199}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005200
Richard Smithf39aec12012-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 Smith097e0a22013-05-21 19:05:48 +00005203bool Sema::ICEConvertDiagnoser::match(QualType T) {
5204 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5205 : T->isIntegralOrUnscopedEnumerationType();
Richard Smithf39aec12012-02-04 07:07:42 +00005206}
5207
Larisse Voufo50b60b32013-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 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005223 return From;
Larisse Voufo50b60b32013-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(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005246 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo50b60b32013-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
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005254 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo50b60b32013-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(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005261 CK_UserDefinedConversion, Result.get(),
5262 nullptr, Result.get()->getValueKind());
Larisse Voufo50b60b32013-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());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005273 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo50b60b32013-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(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005290 CK_UserDefinedConversion, Result.get(),
5291 nullptr, Result.get()->getValueKind());
Larisse Voufo50b60b32013-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 Gregor1ce55092013-11-07 22:34:54 +00005325 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5326 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005327 else
5328 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor1ce55092013-11-07 22:34:54 +00005329 ToType, CandidateSet,
5330 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005331 }
5332}
5333
Richard Smith097e0a22013-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 Gregorc30614b2010-06-29 23:17:37 +00005336///
Richard Smith097e0a22013-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 Gregorc30614b2010-06-29 23:17:37 +00005342///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005343/// \param Loc The source location of the construct that requires the
5344/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005345///
James Dennett40ae6662012-06-22 08:52:37 +00005346/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005347///
Richard Smith097e0a22013-05-21 19:05:48 +00005348/// \param Converter Used to control and diagnose the conversion process.
Richard Smithf39aec12012-02-04 07:07:42 +00005349///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005350/// \returns The expression, converted to an integral or enumeration type if
5351/// successful.
Richard Smith097e0a22013-05-21 19:05:48 +00005352ExprResult Sema::PerformContextualImplicitConversion(
5353 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005354 // We can't perform any more checking for type-dependent expressions.
5355 if (From->isTypeDependent())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005356 return From;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005357
Eli Friedmanceccab92012-01-26 00:26:18 +00005358 // Process placeholders immediately.
5359 if (From->hasPlaceholderType()) {
5360 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005361 if (result.isInvalid())
5362 return result;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005363 From = result.get();
Eli Friedmanceccab92012-01-26 00:26:18 +00005364 }
5365
Richard Smith097e0a22013-05-21 19:05:48 +00005366 // If the expression already has a matching type, we're golden.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005367 QualType T = From->getType();
Richard Smith097e0a22013-05-21 19:05:48 +00005368 if (Converter.match(T))
Eli Friedmanceccab92012-01-26 00:26:18 +00005369 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005370
5371 // FIXME: Check for missing '()' if T is a function type?
5372
Richard Smith097e0a22013-05-21 19:05:48 +00005373 // We can only perform contextual implicit conversions on objects of class
5374 // type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005375 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005376 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smith097e0a22013-05-21 19:05:48 +00005377 if (!Converter.Suppress)
5378 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005379 return From;
Douglas Gregorc30614b2010-06-29 23:17:37 +00005380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005381
Douglas Gregorc30614b2010-06-29 23:17:37 +00005382 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005383 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smith097e0a22013-05-21 19:05:48 +00005384 ContextualImplicitConverter &Converter;
Douglas Gregorab41fe92012-05-04 22:38:52 +00005385 Expr *From;
Richard Smith097e0a22013-05-21 19:05:48 +00005386
5387 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5388 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5389
Stephen Hines651f13c2014-04-23 16:59:28 -07005390 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smith097e0a22013-05-21 19:05:48 +00005391 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005392 }
Richard Smith097e0a22013-05-21 19:05:48 +00005393 } IncompleteDiagnoser(Converter, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005394
5395 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005396 return From;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005397
Douglas Gregorc30614b2010-06-29 23:17:37 +00005398 // Look for a conversion to an integral or enumeration type.
Larisse Voufo50b60b32013-06-10 06:50:24 +00005399 UnresolvedSet<4>
5400 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005401 UnresolvedSet<4> ExplicitConversions;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005402 const auto &Conversions =
Larisse Voufo50b60b32013-06-10 06:50:24 +00005403 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005404
Larisse Voufo50b60b32013-06-10 06:50:24 +00005405 bool HadMultipleCandidates =
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005406 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005407
Larisse Voufo50b60b32013-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.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005413 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo50b60b32013-06-10 06:50:24 +00005414 NamedDecl *D = (*I)->getUnderlyingDecl();
5415 CXXConversionDecl *Conversion;
5416 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5417 if (ConvTemplate) {
Stephen Hines176edba2014-12-01 14:53:08 -08005418 if (getLangOpts().CPlusPlus14)
Larisse Voufo50b60b32013-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
Stephen Hines176edba2014-12-01 14:53:08 -08005425 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo50b60b32013-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 Gregorc30614b2010-06-29 23:17:37 +00005436 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo50b60b32013-06-10 06:50:24 +00005437 } else {
Stephen Hines176edba2014-12-01 14:53:08 -08005438 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo50b60b32013-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 Gregorc30614b2010-06-29 23:17:37 +00005446 }
Richard Smithf39aec12012-02-04 07:07:42 +00005447 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005448 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005449
Stephen Hines176edba2014-12-01 14:53:08 -08005450 if (getLangOpts().CPlusPlus14) {
Larisse Voufo50b60b32013-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 Voufo7acc5a62013-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 Voufo50b60b32013-06-10 06:50:24 +00005458 // exactly one such T.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005459
Larisse Voufo50b60b32013-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 Gregorc30614b2010-06-29 23:17:37 +00005465 return ExprError();
Larisse Voufo50b60b32013-06-10 06:50:24 +00005466 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005467 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005468
Larisse Voufo50b60b32013-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 Takumidfbb02a2011-01-27 07:10:08 +00005473
Larisse Voufo50b60b32013-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.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005477 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005478 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5479 CandidateSet);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005480
Larisse Voufo50b60b32013-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 Gregor6bc574d2010-06-30 00:20:43 +00005512 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005513
Larisse Voufo50b60b32013-06-10 06:50:24 +00005514 // We'll complain below about a non-integral condition type.
5515 break;
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005516 }
Larisse Voufo50b60b32013-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 Gregorc30614b2010-06-29 23:17:37 +00005529 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005530
Larisse Voufo50b60b32013-06-10 06:50:24 +00005531 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005532}
5533
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005534/// 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 Gregor8e9bebd2008-10-21 16:13:35 +00005573/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-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 Gregor9c6a0e92009-09-22 15:41:20 +00005577///
James Dennett699c9042012-06-15 07:13:21 +00005578/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005579/// based on an incomplete set of function arguments. This feature is used by
5580/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005581void
5582Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005583 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005584 ArrayRef<Expr *> Args,
Stephen Hines651f13c2014-04-23 16:59:28 -07005585 OverloadCandidateSet &CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005586 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005587 bool PartialOverloading,
5588 bool AllowExplicit) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005589 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00005590 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005591 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005592 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005593 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005594
Douglas Gregor88a35142008-12-22 05:46:06 +00005595 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-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 McCall701c89e2009-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 McCall9aa472c2010-03-19 07:35:19 +00005604 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005605 QualType(), Expr::Classification::makeSimpleLValue(),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005606 Args, CandidateSet, SuppressUserConversions,
5607 PartialOverloading);
Sebastian Redl3201f6b2009-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 Gregor88a35142008-12-22 05:46:06 +00005612 }
5613
Douglas Gregorfd476482009-11-13 23:59:09 +00005614 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005615 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005616
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005617 // 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 Smith743cbb92013-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 Gregor7edfb692009-11-23 12:27:39 +00005636 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005637 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005638
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005639 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005640 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005641 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005642 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005643 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005644 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005645 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005646 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005647
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005648 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
Stephen Hines651f13c2014-04-23 16:59:28 -07005663 unsigned NumParams = Proto->getNumParams();
Douglas Gregor8e9bebd2008-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).
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005668 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005669 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005670 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005671 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-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 Charles13a140c2012-02-25 11:00:22 +00005681 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005682 // Not enough arguments.
5683 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005684 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005685 return;
5686 }
5687
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005688 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005689 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005690 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Stephen Hines176edba2014-12-01 14:53:08 -08005691 // 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 Collingbourne78dd67e2011-10-02 23:49:40 +00005696 Candidate.Viable = false;
5697 Candidate.FailureKind = ovl_fail_bad_target;
5698 return;
5699 }
5700
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005701 // Determine the implicit conversion sequences for each of the
5702 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005703 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005704 if (ArgIdx < NumParams) {
Douglas Gregor8e9bebd2008-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07005709 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005710 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005711 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005712 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005713 /*InOverloadResolution=*/true,
5714 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005715 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005716 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005717 if (Candidate.Conversions[ArgIdx].isBad()) {
5718 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005719 Candidate.FailureKind = ovl_fail_bad_conversion;
Stephen Hines651f13c2014-04-23 16:59:28 -07005720 return;
Douglas Gregor96176b32008-11-18 23:14:02 +00005721 }
Douglas Gregor8e9bebd2008-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 McCall1d318332010-01-12 00:44:57 +00005726 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005727 }
5728 }
Stephen Hines651f13c2014-04-23 16:59:28 -07005729
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
Stephen Hines176edba2014-12-01 14:53:08 -08005738ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
5739 bool IsInstance) {
5740 SmallVector<ObjCMethodDecl*, 4> Methods;
5741 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5742 return nullptr;
5743
5744 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 }
5804 } else {
5805 // Check for extra arguments to non-variadic methods.
5806 if (Args.size() != NumNamedArgs)
5807 Match = false;
5808 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 }
5818
5819 if (Match)
5820 return Method;
5821 }
5822 return nullptr;
5823}
5824
Stephen Hines651f13c2014-04-23 16:59:28 -07005825static 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())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005832 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07005833 AttrVec Attrs = Function->getAttrs();
5834 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5835 IsNotEnableIfAttr);
5836 if (Attrs.begin() == E)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005837 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07005838 std::reverse(Attrs.begin(), E);
5839
5840 SFINAETrap Trap(*this);
5841
5842 // Convert the arguments.
5843 SmallVector<Expr *, 16> ConvertedArgs;
5844 bool InitializationFailed = false;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005845 bool ContainsValueDependentExpr = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07005846 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5847 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5848 !cast<CXXMethodDecl>(Function)->isStatic() &&
5849 !isa<CXXConstructorDecl>(Function)) {
5850 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5851 ExprResult R =
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005852 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Stephen Hines651f13c2014-04-23 16:59:28 -07005853 Method, Method);
5854 if (R.isInvalid()) {
5855 InitializationFailed = true;
5856 break;
5857 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005858 ContainsValueDependentExpr |= R.get()->isValueDependent();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005859 ConvertedArgs.push_back(R.get());
Stephen Hines651f13c2014-04-23 16:59:28 -07005860 } 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 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005871 ContainsValueDependentExpr |= R.get()->isValueDependent();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005872 ConvertedArgs.push_back(R.get());
Stephen Hines651f13c2014-04-23 16:59:28 -07005873 }
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);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005882 if (EIA->getCond()->isValueDependent()) {
5883 // Don't even try now, we'll examine it after instantiation.
5884 continue;
5885 }
5886
Stephen Hines651f13c2014-04-23 16:59:28 -07005887 if (!EIA->getCond()->EvaluateWithSubstitution(
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005888 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5889 if (!ContainsValueDependentExpr)
5890 return EIA;
5891 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005892 return EIA;
5893 }
5894 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005895 return nullptr;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005896}
5897
Douglas Gregor063daf62009-03-13 18:40:31 +00005898/// \brief Add all of the function declarations in the given function set to
Nick Lewycky199e3702013-09-22 10:06:01 +00005899/// the overload candidate set.
John McCall6e266892010-01-26 03:27:55 +00005900void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005901 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005902 OverloadCandidateSet& CandidateSet,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005903 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005904 bool SuppressUserConversions,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005905 bool PartialOverloading) {
John McCall6e266892010-01-26 03:27:55 +00005906 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005907 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5908 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005909 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005910 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005911 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005912 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005913 Args.slice(1), CandidateSet,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005914 SuppressUserConversions, PartialOverloading);
Douglas Gregor3f396022009-09-28 04:47:19 +00005915 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005916 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005917 SuppressUserConversions, PartialOverloading);
Douglas Gregor3f396022009-09-28 04:47:19 +00005918 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005919 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005920 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5921 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005922 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005923 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005924 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005925 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005926 Args[0]->Classify(Context), Args.slice(1),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005927 CandidateSet, SuppressUserConversions,
5928 PartialOverloading);
Douglas Gregor3f396022009-09-28 04:47:19 +00005929 else
John McCall9aa472c2010-03-19 07:35:19 +00005930 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005931 ExplicitTemplateArgs, Args,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005932 CandidateSet, SuppressUserConversions,
5933 PartialOverloading);
Douglas Gregor3f396022009-09-28 04:47:19 +00005934 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005935 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005936}
5937
John McCall314be4e2009-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 McCall9aa472c2010-03-19 07:35:19 +00005940void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005941 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005942 Expr::Classification ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005943 ArrayRef<Expr *> Args,
John McCall314be4e2009-11-17 07:50:12 +00005944 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005945 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005946 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005947 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005948
5949 if (isa<UsingShadowDecl>(Decl))
5950 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005951
John McCall314be4e2009-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 McCall9aa472c2010-03-19 07:35:19 +00005955 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005956 /*ExplicitArgs*/ nullptr,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005957 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005958 Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005959 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005960 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005961 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005962 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005963 Args,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005964 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005965 }
5966}
5967
Douglas Gregor96176b32008-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 Gregor7ec77522010-04-16 17:33:27 +00005974/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005975void
John McCall9aa472c2010-03-19 07:35:19 +00005976Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005977 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005978 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005979 ArrayRef<Expr *> Args,
Stephen Hines651f13c2014-04-23 16:59:28 -07005980 OverloadCandidateSet &CandidateSet,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005981 bool SuppressUserConversions,
5982 bool PartialOverloading) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005983 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00005984 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005985 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005986 assert(!isa<CXXConstructorDecl>(Method) &&
5987 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005988
Douglas Gregor3f396022009-09-28 04:47:19 +00005989 if (!CandidateSet.isNewCandidate(Method))
5990 return;
5991
Richard Smith743cbb92013-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 Gregor7edfb692009-11-23 12:27:39 +00005999 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006000 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006001
Douglas Gregor96176b32008-11-18 23:14:02 +00006002 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00006003 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00006004 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00006005 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006006 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006007 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006008 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00006009
Stephen Hines651f13c2014-04-23 16:59:28 -07006010 unsigned NumParams = Proto->getNumParams();
Douglas Gregor96176b32008-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).
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006015 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6016 !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006017 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006018 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-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();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006028 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006029 // Not enough arguments.
6030 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006031 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00006032 return;
6033 }
6034
6035 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00006036
John McCall701c89e2009-12-03 04:06:58 +00006037 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-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 McCall701c89e2009-12-03 04:06:58 +00006043 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006044 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6045 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00006046 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00006047 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006048 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00006049 return;
6050 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006051 }
6052
Stephen Hines176edba2014-12-01 14:53:08 -08006053 // (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 Gregor96176b32008-11-18 23:14:02 +00006062 // Determine the implicit conversion sequences for each of the
6063 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00006064 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Stephen Hines651f13c2014-04-23 16:59:28 -07006065 if (ArgIdx < NumParams) {
Douglas Gregor96176b32008-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07006070 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00006071 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006072 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006073 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00006074 /*InOverloadResolution=*/true,
6075 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006076 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00006077 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006078 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006079 Candidate.FailureKind = ovl_fail_bad_conversion;
Stephen Hines651f13c2014-04-23 16:59:28 -07006080 return;
Douglas Gregor96176b32008-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
Stephen Hines651f13c2014-04-23 16:59:28 -07006085 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00006086 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00006087 }
6088 }
Stephen Hines651f13c2014-04-23 16:59:28 -07006089
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 Gregor96176b32008-11-18 23:14:02 +00006096}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006097
Douglas Gregor6b906862009-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 Stump1eb44332009-09-09 15:08:12 +00006101void
Douglas Gregor6b906862009-08-21 00:16:32 +00006102Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00006103 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006104 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00006105 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00006106 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006107 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006108 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00006109 OverloadCandidateSet& CandidateSet,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006110 bool SuppressUserConversions,
6111 bool PartialOverloading) {
Douglas Gregor3f396022009-09-28 04:47:19 +00006112 if (!CandidateSet.isNewCandidate(MethodTmpl))
6113 return;
6114
Douglas Gregor6b906862009-08-21 00:16:32 +00006115 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00006116 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00006117 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00006118 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-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 Topper93e45992012-09-19 02:26:47 +00006124 TemplateDeductionInfo Info(CandidateSet.getLocation());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006125 FunctionDecl *Specialization = nullptr;
Douglas Gregor6b906862009-08-21 00:16:32 +00006126 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00006127 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006128 Specialization, Info, PartialOverloading)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006129 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-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 Charles13a140c2012-02-25 11:00:22 +00006136 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006137 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00006138 Info);
6139 return;
6140 }
Mike Stump1eb44332009-09-09 15:08:12 +00006141
Douglas Gregor6b906862009-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 Stump1eb44332009-09-09 15:08:12 +00006145 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00006146 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00006147 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00006148 ActingContext, ObjectType, ObjectClassification, Args,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006149 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor6b906862009-08-21 00:16:32 +00006150}
6151
Douglas Gregor65ec1fd2009-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 Stump1eb44332009-09-09 15:08:12 +00006155void
Douglas Gregore53060f2009-06-25 22:08:12 +00006156Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00006157 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00006158 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006159 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00006160 OverloadCandidateSet& CandidateSet,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006161 bool SuppressUserConversions,
6162 bool PartialOverloading) {
Douglas Gregor3f396022009-09-28 04:47:19 +00006163 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6164 return;
6165
Douglas Gregore53060f2009-06-25 22:08:12 +00006166 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00006167 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00006168 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00006169 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-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 Topper93e45992012-09-19 02:26:47 +00006175 TemplateDeductionInfo Info(CandidateSet.getLocation());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006176 FunctionDecl *Specialization = nullptr;
Douglas Gregore53060f2009-06-25 22:08:12 +00006177 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00006178 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006179 Specialization, Info, PartialOverloading)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006180 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00006181 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00006182 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6183 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006184 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00006185 Candidate.IsSurrogate = false;
6186 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006187 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006188 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00006189 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00006190 return;
6191 }
Mike Stump1eb44332009-09-09 15:08:12 +00006192
Douglas Gregore53060f2009-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 Charles13a140c2012-02-25 11:00:22 +00006196 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006197 SuppressUserConversions, PartialOverloading);
Douglas Gregore53060f2009-06-25 22:08:12 +00006198}
Mike Stump1eb44332009-09-09 15:08:12 +00006199
Douglas Gregor1ce55092013-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 Gregorf1991ea2008-11-07 22:36:19 +00006239/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00006240/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006241/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00006242/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-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 McCall9aa472c2010-03-19 07:35:19 +00006247 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006248 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006249 Expr *From, QualType ToType,
Douglas Gregor1ce55092013-11-07 22:34:54 +00006250 OverloadCandidateSet& CandidateSet,
6251 bool AllowObjCConversionOnExplicit) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006252 assert(!Conversion->getDescribedFunctionTemplate() &&
6253 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00006254 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00006255 if (!CandidateSet.isNewCandidate(Conversion))
6256 return;
6257
Richard Smith60e141e2013-05-04 07:00:32 +00006258 // If the conversion function has an undeduced return type, trigger its
6259 // deduction now.
Stephen Hines176edba2014-12-01 14:53:08 -08006260 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith60e141e2013-05-04 07:00:32 +00006261 if (DeduceReturnType(Conversion, From->getExprLoc()))
6262 return;
6263 ConvType = Conversion->getConversionType().getNonReferenceType();
6264 }
6265
Richard Smithb390e492013-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 Gregor1ce55092013-11-07 22:34:54 +00006269 if (Conversion->isExplicit() &&
6270 !isAllowableExplicitConversion(*this, ConvType, ToType,
6271 AllowObjCConversionOnExplicit))
Richard Smithb390e492013-09-21 21:55:46 +00006272 return;
6273
Douglas Gregor7edfb692009-11-23 12:27:39 +00006274 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006275 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006276
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006277 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006278 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00006279 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006280 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006281 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006282 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006283 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00006284 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00006285 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006286 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00006287 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00006288
Douglas Gregorbca39322010-08-19 15:37:02 +00006289 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-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 Gregorbca39322010-08-19 15:37:02 +00006292 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-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 Takumidfbb02a2011-01-27 07:10:08 +00006301
Douglas Gregorc774b2f2010-08-19 15:57:50 +00006302 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006303 = TryObjectArgumentInitialization(*this, From->getType(),
6304 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006305 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006306
John McCall1d318332010-01-12 00:44:57 +00006307 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006308 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006309 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006310 return;
6311 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00006312
Stephen Hines651f13c2014-04-23 16:59:28 -07006313 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian3759a032009-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 McCall717e8912010-01-23 05:17:32 +00006321 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00006322 return;
6323 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006324
Douglas Gregorf1991ea2008-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 McCallf4b88a42012-03-10 09:33:50 +00006333 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00006334 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00006335 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6336 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00006337 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00006338 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00006339
Richard Smith87c1f1f2011-07-13 22:53:21 +00006340 QualType ConversionType = Conversion->getConversionType();
6341 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00006342 Candidate.Viable = false;
6343 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6344 return;
6345 }
6346
Richard Smith87c1f1f2011-07-13 22:53:21 +00006347 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00006348
Mike Stump1eb44332009-09-09 15:08:12 +00006349 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00006350 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6351 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00006352 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00006353 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00006354 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00006355 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00006356 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00006357 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00006358 /*InOverloadResolution=*/false,
6359 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00006360
John McCall1d318332010-01-12 00:44:57 +00006361 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006362 case ImplicitConversionSequence::StandardConversion:
6363 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006364
Douglas Gregorc520c842010-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 Takumidfbb02a2011-01-27 07:10:08 +00006367 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-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;
Stephen Hines651f13c2014-04-23 16:59:28 -07006373 return;
Douglas Gregorc520c842010-04-12 23:42:09 +00006374 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006375
Douglas Gregor2ad746a2011-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 Takumidfbb02a2011-01-27 07:10:08 +00006381 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-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;
Stephen Hines651f13c2014-04-23 16:59:28 -07006385 return;
Douglas Gregor2ad746a2011-01-21 05:18:22 +00006386 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006387 break;
6388
6389 case ImplicitConversionSequence::BadConversion:
6390 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00006391 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Stephen Hines651f13c2014-04-23 16:59:28 -07006392 return;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006393
6394 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006395 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006396 "Can only end up with a standard conversion sequence or failure");
6397 }
Stephen Hines651f13c2014-04-23 16:59:28 -07006398
Stephen Hines176edba2014-12-01 14:53:08 -08006399 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07006400 Candidate.Viable = false;
6401 Candidate.FailureKind = ovl_fail_enable_if;
6402 Candidate.DeductionFailure.Data = FailedAttr;
6403 return;
6404 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006405}
6406
Douglas Gregor65ec1fd2009-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 Stump1eb44332009-09-09 15:08:12 +00006412void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006413Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00006414 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006415 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006416 Expr *From, QualType ToType,
Douglas Gregor1ce55092013-11-07 22:34:54 +00006417 OverloadCandidateSet &CandidateSet,
6418 bool AllowObjCConversionOnExplicit) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006419 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6420 "Only conversion function templates permitted here");
6421
Douglas Gregor3f396022009-09-28 04:47:19 +00006422 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6423 return;
6424
Craig Topper93e45992012-09-19 02:26:47 +00006425 TemplateDeductionInfo Info(CandidateSet.getLocation());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006426 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006427 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00006428 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006429 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006430 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-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 Gregordfc331e2011-01-19 23:54:39 +00006437 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006438 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00006439 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006440 return;
6441 }
Mike Stump1eb44332009-09-09 15:08:12 +00006442
Douglas Gregor65ec1fd2009-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 McCall9aa472c2010-03-19 07:35:19 +00006446 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor1ce55092013-11-07 22:34:54 +00006447 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006448}
6449
Douglas Gregor106c6eb2008-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 McCall9aa472c2010-03-19 07:35:19 +00006456 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006457 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00006458 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006459 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006460 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006461 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00006462 if (!CandidateSet.isNewCandidate(Conversion))
6463 return;
6464
Douglas Gregor7edfb692009-11-23 12:27:39 +00006465 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006466 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006467
Ahmed Charles13a140c2012-02-25 11:00:22 +00006468 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00006469 Candidate.FoundDecl = FoundDecl;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006470 Candidate.Function = nullptr;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006471 Candidate.Surrogate = Conversion;
6472 Candidate.Viable = true;
6473 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00006474 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006475 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006476
6477 // Determine the implicit conversion sequence for the implicit
6478 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00006479 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006480 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006481 Object->Classify(Context),
6482 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00006483 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006484 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006485 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00006486 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-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 McCall1d318332010-01-12 00:44:57 +00006493 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006494 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00006495 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00006496 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006497 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00006498 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00006499 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006500 = Candidate.Conversions[0].UserDefined.Before;
6501 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6502
Mike Stump1eb44332009-09-09 15:08:12 +00006503 // Find the
Stephen Hines651f13c2014-04-23 16:59:28 -07006504 unsigned NumParams = Proto->getNumParams();
Douglas Gregor106c6eb2008-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).
Stephen Hines651f13c2014-04-23 16:59:28 -07006509 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006510 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006511 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07006517 if (Args.size() < NumParams) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006518 // Not enough arguments.
6519 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006520 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006521 return;
6522 }
6523
6524 // Determine the implicit conversion sequences for each of the
6525 // arguments.
Richard Smith958ba642013-05-05 15:51:06 +00006526 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Stephen Hines651f13c2014-04-23 16:59:28 -07006527 if (ArgIdx < NumParams) {
Douglas Gregor106c6eb2008-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.
Stephen Hines651f13c2014-04-23 16:59:28 -07006532 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00006533 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006534 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00006535 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00006536 /*InOverloadResolution=*/false,
6537 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006538 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00006539 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006540 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006541 Candidate.FailureKind = ovl_fail_bad_conversion;
Stephen Hines651f13c2014-04-23 16:59:28 -07006542 return;
Douglas Gregor106c6eb2008-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 McCall1d318332010-01-12 00:44:57 +00006548 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006549 }
6550 }
Stephen Hines651f13c2014-04-23 16:59:28 -07006551
Stephen Hines176edba2014-12-01 14:53:08 -08006552 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07006553 Candidate.Viable = false;
6554 Candidate.FailureKind = ovl_fail_enable_if;
6555 Candidate.DeductionFailure.Data = FailedAttr;
6556 return;
6557 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006558}
6559
Douglas Gregor063daf62009-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 Smith958ba642013-05-05 15:51:06 +00006570 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00006571 OverloadCandidateSet& CandidateSet,
6572 SourceRange OpRange) {
Douglas Gregor96176b32008-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 Gregor96176b32008-11-18 23:14:02 +00006584
Richard Smithe410be92013-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 Kremenek6217b802009-07-29 21:53:49 +00006589 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smithe410be92013-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 Gregor8a5ae242009-08-27 23:35:55 +00006594 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006595
John McCalla24dc2e2009-11-17 02:14:36 +00006596 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6597 LookupQualifiedName(Operators, T1Rec->getDecl());
6598 Operators.suppressDiagnostics();
6599
Mike Stump1eb44332009-09-09 15:08:12 +00006600 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006601 OperEnd = Operators.end();
6602 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006603 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006604 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola548107e2013-04-29 19:29:25 +00006605 Args[0]->Classify(Context),
Richard Smith958ba642013-05-05 15:51:06 +00006606 Args.slice(1),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006607 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006608 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006609 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006610}
6611
Douglas Gregoreb8f3062008-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 Gregor88b4bf22009-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 Gregor09f41cf2009-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 Stump1eb44332009-09-09 15:08:12 +00006620void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smith958ba642013-05-05 15:51:06 +00006621 ArrayRef<Expr *> Args,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006622 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006623 bool IsAssignmentOperator,
6624 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006625 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006626 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006627
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006628 // Add this candidate
Richard Smith958ba642013-05-05 15:51:06 +00006629 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006630 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6631 Candidate.Function = nullptr;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006632 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006633 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006634 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smith958ba642013-05-05 15:51:06 +00006635 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregoreb8f3062008-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 Smith958ba642013-05-05 15:51:06 +00006641 Candidate.ExplicitCallArguments = Args.size();
6642 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor88b4bf22009-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 Stump1eb44332009-09-09 15:08:12 +00006649 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-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 Gregor09f41cf2009-01-14 15:45:31 +00006655 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006656 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006657 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006658 Candidate.Conversions[ArgIdx]
6659 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006660 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006661 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006662 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006663 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006664 /*InOverloadResolution=*/false,
6665 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006666 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006667 }
John McCall1d318332010-01-12 00:44:57 +00006668 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006669 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006670 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006671 break;
6672 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006673 }
6674}
6675
Craig Topperfe09f3f2013-07-01 06:29:40 +00006676namespace {
6677
Douglas Gregoreb8f3062008-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 Lattnere37b94c2009-03-29 00:04:01 +00006684 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-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 Redl78eb8742009-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 Gregoreb8f3062008-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 Takumidfbb02a2011-01-27 07:10:08 +00006698 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006699 /// candidates.
6700 TypeSet VectorTypes;
Chandler Carruth6a577462010-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 Gregor84ee2ee2011-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 Gregor5842ba92009-08-24 15:23:48 +00006713 /// Sema - The semantic analysis instance where we are building the
6714 /// candidate type set.
6715 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006716
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006717 /// Context - The AST context in which we will build the type sets.
6718 ASTContext &Context;
6719
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006720 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6721 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006722 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006723
6724public:
6725 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006726 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006727
Mike Stump1eb44332009-09-09 15:08:12 +00006728 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006729 : HasNonRecordTypes(false),
6730 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006731 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006732 SemaRef(SemaRef),
6733 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006734
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006735 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006736 SourceLocation Loc,
6737 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006738 bool AllowExplicitConversions,
6739 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006740
6741 /// pointer_begin - First pointer type found;
6742 iterator pointer_begin() { return PointerTypes.begin(); }
6743
Sebastian Redl78eb8742009-04-19 21:53:20 +00006744 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006745 iterator pointer_end() { return PointerTypes.end(); }
6746
Sebastian Redl78eb8742009-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 Gregoreb8f3062008-11-12 17:17:38 +00006753 /// enumeration_begin - First enumeration type found;
6754 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6755
Sebastian Redl78eb8742009-04-19 21:53:20 +00006756 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006757 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006758
Douglas Gregor26bcf672010-05-19 03:21:00 +00006759 iterator vector_begin() { return VectorTypes.begin(); }
6760 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006761
6762 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6763 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006764 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006765};
6766
Craig Topperfe09f3f2013-07-01 06:29:40 +00006767} // end anonymous namespace
6768
Sebastian Redl78eb8742009-04-19 21:53:20 +00006769/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-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 McCall0953e762009-09-24 19:53:00 +00006776///
6777/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006778bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006779BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6780 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006781
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006782 // Insert this type.
Stephen Hines176edba2014-12-01 14:53:08 -08006783 if (!PointerTypes.insert(Ty).second)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006784 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006785
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006786 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006787 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006788 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006789 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006790 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6791 PointeeTy = PTy->getPointeeType();
6792 buildObjCPtr = true;
6793 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006794 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006795 }
6796
Sebastian Redla9efada2009-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 Gregorb1c6f5f2012-06-04 00:15:09 +00006803
John McCall0953e762009-09-24 19:53:00 +00006804 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006805 bool hasVolatile = VisibleQuals.hasVolatile();
6806 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006807
John McCall0953e762009-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 Gregorb1c6f5f2012-06-04 00:15:09 +00006811 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006812 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-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 McCall0953e762009-09-24 19:53:00 +00006822 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006823
6824 // Build qualified pointer type.
6825 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006826 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006827 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006828 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006829 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6830
6831 // Insert qualified pointer type.
6832 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006833 }
6834
6835 return true;
6836}
6837
Sebastian Redl78eb8742009-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 McCall0953e762009-09-24 19:53:00 +00006845///
6846/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006847bool
6848BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6849 QualType Ty) {
6850 // Insert this type.
Stephen Hines176edba2014-12-01 14:53:08 -08006851 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl78eb8742009-04-19 21:53:20 +00006852 return false;
6853
John McCall0953e762009-09-24 19:53:00 +00006854 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6855 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006856
John McCall0953e762009-09-24 19:53:00 +00006857 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-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 McCall0953e762009-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 Takumidfbb02a2011-01-27 07:10:08 +00006871
John McCall0953e762009-09-24 19:53:00 +00006872 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006873 MemberPointerTypes.insert(
6874 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006875 }
6876
6877 return true;
6878}
6879
Douglas Gregoreb8f3062008-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 Redl78eb8742009-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 Gregor09f41cf2009-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 Stump1eb44332009-09-09 15:08:12 +00006888void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006889BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006890 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006891 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006892 bool AllowExplicitConversions,
6893 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-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 Kremenek6217b802009-07-29 21:53:49 +00006899 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006900 Ty = RefTy->getPointeeType();
6901
John McCall3b657512011-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 Gregora4923eb2009-11-16 21:35:15 +00006907 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006908
Chandler Carruth6a577462010-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 Carruth6a577462010-12-13 01:44:01 +00006913 // Flag if we encounter an arithmetic type.
6914 HasArithmeticOrEnumeralTypes =
6915 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6916
Fariborz Jahanian2e2acec2010-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 Gregoreb8f3062008-11-12 17:17:38 +00006920 // Insert our type, and its more-qualified variants, into the set
6921 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006922 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006923 return;
Sebastian Redl78eb8742009-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 Gregoreb8f3062008-11-12 17:17:38 +00006928 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006929 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006930 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006931 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006932 // We treat vector types as arithmetic types in many contexts as an
6933 // extension.
6934 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006935 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006936 } else if (Ty->isNullPtrType()) {
6937 HasNullPtrType = true;
Chandler Carruth6a577462010-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 Stump1eb44332009-09-09 15:08:12 +00006942
Chandler Carruth6a577462010-12-13 01:44:01 +00006943 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006944 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006945 if (isa<UsingShadowDecl>(D))
6946 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006947
Chandler Carruth6a577462010-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 Gregor65ec1fd2009-08-21 23:19:43 +00006952
Chandler Carruth6a577462010-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 Gregoreb8f3062008-11-12 17:17:38 +00006957 }
6958 }
6959 }
6960}
6961
Douglas Gregor19b7b152009-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 Smith958ba642013-05-05 15:51:06 +00006967 ArrayRef<Expr *> Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006968 OverloadCandidateSet &CandidateSet) {
6969 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006970
Douglas Gregor19b7b152009-08-24 13:43:27 +00006971 // T& operator=(T&, T)
6972 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6973 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006974 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006975 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006976
Douglas Gregor19b7b152009-08-24 13:43:27 +00006977 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6978 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006979 ParamTypes[0]
6980 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006981 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006982 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006983 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006984 }
6985}
Mike Stump1eb44332009-09-09 15:08:12 +00006986
Sebastian Redl9994a342009-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 Jahaniana9cca892009-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 Gregorb86cf0c2010-04-25 00:55:24 +00006994 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006995 else
6996 TyRec = ArgExpr->getType()->getAs<RecordType>();
6997 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006998 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006999 VRQuals.addVolatile();
7000 VRQuals.addRestrict();
7001 return VRQuals;
7002 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007003
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007004 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00007005 if (!ClassDecl->hasDefinition())
7006 return VRQuals;
7007
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007008 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCall32daa422010-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 Jahaniana9cca892009-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 Gregorb1c6f5f2012-06-04 00:15:09 +00007019 if (CanTy.isRestrictQualified())
7020 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007021 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7022 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007023 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-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 Jahaniana9cca892009-10-15 17:14:05 +00007030 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7031 return VRQuals;
7032 }
7033 }
7034 }
7035 return VRQuals;
7036}
John McCall00071ec2010-11-13 05:51:15 +00007037
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007038namespace {
John McCall00071ec2010-11-13 05:51:15 +00007039
Chandler Carruth3a0f3ef2010-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 Carruth6d695582010-12-12 10:35:00 +00007045 // Common instance state available to all overload candidate addition methods.
7046 Sema &S;
Richard Smith958ba642013-05-05 15:51:06 +00007047 ArrayRef<Expr *> Args;
Chandler Carruth6d695582010-12-12 10:35:00 +00007048 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00007049 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007050 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00007051 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007052
Chandler Carruth6d695582010-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 McCall00071ec2010-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 McCall00071ec2010-11-13 05:51:15 +00007057 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00007058 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00007059 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00007060 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00007061 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00007062 LastPromotedArithmeticType = 11;
7063 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00007064
Chandler Carruth6d695582010-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 McCall00071ec2010-11-13 05:51:15 +00007074
Chandler Carruth6d695582010-12-12 10:35:00 +00007075 // Start of integral types.
7076 &ASTContext::IntTy,
7077 &ASTContext::LongTy,
7078 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00007079 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00007080 &ASTContext::UnsignedIntTy,
7081 &ASTContext::UnsignedLongTy,
7082 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00007083 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-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 Smith3c2fcf82012-06-10 08:00:26 +00007096 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00007097 };
7098 return S.Context.*ArithmeticTypes[index];
7099 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007100
Chandler Carruth38ca8d12010-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 Smith3c2fcf82012-06-10 08:00:26 +00007115 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007116 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00007117 Dep=-1,
7118 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007119 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00007120 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007121 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-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 Carruth38ca8d12010-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 Carruth6d695582010-12-12 10:35:00 +00007140 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-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 Carruth6d695582010-12-12 10:35:00 +00007144 CanQualType LT = getArithmeticType(L),
7145 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-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 Carruth3c69dc42010-12-12 09:22:45 +00007159 /// \brief Helper method to factor out the common pattern of adding overloads
7160 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007161 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007162 bool HasVolatile,
7163 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00007170 if (Args.size() == 1)
7171 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007172 else
Richard Smith958ba642013-05-05 15:51:06 +00007173 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00007181 if (Args.size() == 1)
7182 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007183 else
Richard Smith958ba642013-05-05 15:51:06 +00007184 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007185 }
Douglas Gregorb1c6f5f2012-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 Smith958ba642013-05-05 15:51:06 +00007194 if (Args.size() == 1)
7195 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007196 else
Richard Smith958ba642013-05-05 15:51:06 +00007197 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-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 Smith958ba642013-05-05 15:51:06 +00007205 if (Args.size() == 1)
7206 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007207 else
Richard Smith958ba642013-05-05 15:51:06 +00007208 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007209 }
7210 }
7211
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007212 }
7213
7214public:
7215 BuiltinOperatorOverloadBuilder(
Richard Smith958ba642013-05-05 15:51:06 +00007216 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007217 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007218 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00007219 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007220 OverloadCandidateSet &CandidateSet)
Richard Smith958ba642013-05-05 15:51:06 +00007221 : S(S), Args(Args),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007222 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00007223 HasArithmeticOrEnumeralCandidateType(
7224 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007225 CandidateTypes(CandidateTypes),
7226 CandidateSet(CandidateSet) {
7227 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00007228 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007229 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00007230 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00007231 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007232 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00007233 assert(getArithmeticType(FirstPromotedArithmeticType)
7234 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007235 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00007236 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00007237 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-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 Carruth6a577462010-12-13 01:44:01 +00007259 if (!HasArithmeticOrEnumeralCandidateType)
7260 return;
7261
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007262 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7263 Arith < NumArithmeticTypes; ++Arith) {
7264 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00007265 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007266 VisibleTypeConversionsQuals.hasVolatile(),
7267 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-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 Gregor2fdc5e82011-01-05 00:13:17 +00007287 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007288 continue;
7289
7290 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007291 (!(*Ptr).isVolatileQualified() &&
7292 VisibleTypeConversionsQuals.hasVolatile()),
7293 (!(*Ptr).isRestrictQualified() &&
7294 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-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 Takumidfbb02a2011-01-27 07:10:08 +00007305 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00007306 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-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 Gregor2fdc5e82011-01-05 00:13:17 +00007315 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7316 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007317
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00007318 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7319 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7320 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007321
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007322 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smith958ba642013-05-05 15:51:06 +00007323 &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Carruth6a577462010-12-13 01:44:01 +00007334 if (!HasArithmeticOrEnumeralCandidateType)
7335 return;
7336
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007337 for (unsigned Arith = FirstPromotedArithmeticType;
7338 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007339 QualType ArithTy = getArithmeticType(Arith);
Richard Smith958ba642013-05-05 15:51:06 +00007340 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00007349 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00007364 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Carruth6a577462010-12-13 01:44:01 +00007374 if (!HasArithmeticOrEnumeralCandidateType)
7375 return;
7376
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007377 for (unsigned Int = FirstPromotedIntegralType;
7378 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007379 QualType IntTy = getArithmeticType(Int);
Richard Smith958ba642013-05-05 15:51:06 +00007380 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00007389 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00007403 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-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.
Stephen Hines176edba2014-12-01 14:53:08 -08007410 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007411 continue;
7412
7413 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00007414 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007415 }
7416 }
7417 }
7418
7419 // C++ [over.built]p15:
7420 //
Douglas Gregor84ee2ee2011-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 Carruth3a0f3ef2010-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 Carruth7b80b4b2010-12-12 09:14:11 +00007430 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-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 Carruth7b80b4b2010-12-12 09:14:11 +00007436 //
Eli Friedman97c67392012-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 Carruth7b80b4b2010-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 Smith958ba642013-05-05 15:51:06 +00007446 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth7b80b4b2010-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 Friedman97c67392012-09-18 21:52:24 +00007455 if (C->Function->isFunctionTemplateSpecialization())
7456 continue;
7457
Chandler Carruth7b80b4b2010-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 Carruth3a0f3ef2010-12-12 08:11:30 +00007476 /// Set of (canonical) types that we've already handled.
7477 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7478
Richard Smith958ba642013-05-05 15:51:06 +00007479 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-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.
Stephen Hines176edba2014-12-01 14:53:08 -08007485 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007486 continue;
7487
7488 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007489 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Carruth7b80b4b2010-12-12 09:14:11 +00007497 // Don't add the same builtin candidate twice, or if a user defined
7498 // candidate exists.
Stephen Hines176edba2014-12-01 14:53:08 -08007499 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007500 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7501 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007502 continue;
7503
7504 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007505 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007506 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007507
7508 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7509 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
Stephen Hines176edba2014-12-01 14:53:08 -08007510 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smith958ba642013-05-05 15:51:06 +00007511 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007512 NullPtrTy))) {
7513 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smith958ba642013-05-05 15:51:06 +00007514 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007515 CandidateSet);
7516 }
7517 }
Chandler Carruth3a0f3ef2010-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 Gregor2fdc5e82011-01-05 00:13:17 +00007551 QualType PointeeTy = (*Ptr)->getPointeeType();
7552 if (!PointeeTy->isObjectType())
7553 continue;
7554
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00007559 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007560 }
7561 if (Op == OO_Minus) {
7562 // ptrdiff_t operator-(T, T);
Stephen Hines176edba2014-12-01 14:53:08 -08007563 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007564 continue;
7565
7566 QualType ParamTypes[2] = { *Ptr, *Ptr };
7567 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smith958ba642013-05-05 15:51:06 +00007568 Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Carruth6a577462010-12-13 01:44:01 +00007604 if (!HasArithmeticOrEnumeralCandidateType)
7605 return;
7606
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007607 for (unsigned Left = FirstPromotedArithmeticType;
7608 Left < LastPromotedArithmeticType; ++Left) {
7609 for (unsigned Right = FirstPromotedArithmeticType;
7610 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007611 QualType LandR[2] = { getArithmeticType(Left),
7612 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007613 QualType Result =
7614 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007615 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007616 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00007639 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Carruth6a577462010-12-13 01:44:01 +00007659 if (!HasArithmeticOrEnumeralCandidateType)
7660 return;
7661
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007662 for (unsigned Left = FirstPromotedIntegralType;
7663 Left < LastPromotedIntegralType; ++Left) {
7664 for (unsigned Right = FirstPromotedIntegralType;
7665 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007666 QualType LandR[2] = { getArithmeticType(Left),
7667 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007668 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7669 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007670 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007671 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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) {
Stephen Hines176edba2014-12-01 14:53:08 -08007692 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007693 continue;
7694
Richard Smith958ba642013-05-05 15:51:06 +00007695 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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) {
Stephen Hines176edba2014-12-01 14:53:08 -08007702 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007703 continue;
7704
Richard Smith958ba642013-05-05 15:51:06 +00007705 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Gregor2fdc5e82011-01-05 00:13:17 +00007737 else if (!(*Ptr)->getPointeeType()->isObjectType())
7738 continue;
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00007745 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007746 /*IsAssigmentOperator=*/ isEqualOp);
7747
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007748 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7749 VisibleTypeConversionsQuals.hasVolatile();
7750 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007751 // volatile version
7752 ParamTypes[0] =
7753 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007754 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007755 /*IsAssigmentOperator=*/isEqualOp);
7756 }
Douglas Gregorb1c6f5f2012-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 Smith958ba642013-05-05 15:51:06 +00007763 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-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 Smith958ba642013-05-05 15:51:06 +00007773 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007774 /*IsAssigmentOperator=*/isEqualOp);
7775 }
7776 }
Chandler Carruth3a0f3ef2010-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.
Stephen Hines176edba2014-12-01 14:53:08 -08007785 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007786 continue;
7787
Chandler Carruth6df868e2010-12-12 08:17:55 +00007788 QualType ParamTypes[2] = {
7789 S.Context.getLValueReferenceType(*Ptr),
7790 *Ptr,
7791 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007792
7793 // non-volatile version
Richard Smith958ba642013-05-05 15:51:06 +00007794 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007795 /*IsAssigmentOperator=*/true);
7796
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007797 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7798 VisibleTypeConversionsQuals.hasVolatile();
7799 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007800 // volatile version
7801 ParamTypes[0] =
7802 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007803 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7804 /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007805 }
Douglas Gregorb1c6f5f2012-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 Smith958ba642013-05-05 15:51:06 +00007812 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7813 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-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 Smith958ba642013-05-05 15:51:06 +00007822 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7823 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007824 }
7825 }
Chandler Carruth3a0f3ef2010-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 Carruth6a577462010-12-13 01:44:01 +00007843 if (!HasArithmeticOrEnumeralCandidateType)
7844 return;
7845
Chandler Carruth3a0f3ef2010-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 Carruth6d695582010-12-12 10:35:00 +00007850 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007851
7852 // Add this built-in operator as a candidate (VQ is empty).
7853 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007854 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007855 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-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 Carruth6d695582010-12-12 10:35:00 +00007861 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007862 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007863 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00007882 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00007889 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-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 Carruth6a577462010-12-13 01:44:01 +00007909 if (!HasArithmeticOrEnumeralCandidateType)
7910 return;
7911
Chandler Carruth3a0f3ef2010-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 Carruth6d695582010-12-12 10:35:00 +00007916 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007917
7918 // Add this built-in operator as a candidate (VQ is empty).
7919 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007920 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007921 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007922 if (VisibleTypeConversionsQuals.hasVolatile()) {
7923 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007924 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007925 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7926 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007927 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00007942 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00007948 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-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 Gregor2fdc5e82011-01-05 00:13:17 +00007970 if (!PointeeType->isObjectType())
7971 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007972
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007973 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7974
7975 // T& operator[](T*, ptrdiff_t)
Richard Smith958ba642013-05-05 15:51:06 +00007976 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Gregor2fdc5e82011-01-05 00:13:17 +00007985 if (!PointeeType->isObjectType())
7986 continue;
7987
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007988 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7989
7990 // T& operator[](ptrdiff_t, T*)
Richard Smith958ba642013-05-05 15:51:06 +00007991 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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 Smith958ba642013-05-05 15:51:06 +00008042 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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) {
Stephen Hines176edba2014-12-01 14:53:08 -08008066 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008067 continue;
8068
8069 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00008070 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-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) {
Stephen Hines176edba2014-12-01 14:53:08 -08008077 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008078 continue;
8079
8080 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00008081 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008082 }
8083
Richard Smith80ad52f2013-01-02 11:42:31 +00008084 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-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
Stephen Hines176edba2014-12-01 14:53:08 -08008092 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008093 continue;
8094
8095 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00008096 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008097 }
8098 }
8099 }
8100 }
8101};
8102
Chandler Carruth3a0f3ef2010-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 Wilhelm834c0582013-08-09 18:02:13 +00008110void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8111 SourceLocation OpLoc,
8112 ArrayRef<Expr *> Args,
8113 OverloadCandidateSet &CandidateSet) {
Douglas Gregoreb8f3062008-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 Carruth6a577462010-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 Jahaniana9cca892009-10-15 17:14:05 +00008118 Qualifiers VisibleTypeConversionsQuals;
8119 VisibleTypeConversionsQuals.addConst();
Richard Smith958ba642013-05-05 15:51:06 +00008120 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanian8621d012009-10-19 21:30:45 +00008121 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00008122
8123 bool HasNonRecordCandidateType = false;
8124 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008125 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smith958ba642013-05-05 15:51:06 +00008126 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07008127 CandidateTypes.emplace_back(*this);
Douglas Gregorfec56e72010-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 Carruth6a577462010-12-13 01:44:01 +00008135 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8136 CandidateTypes[ArgIdx].hasNonRecordTypes();
8137 HasArithmeticOrEnumeralCandidateType =
8138 HasArithmeticOrEnumeralCandidateType ||
8139 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00008140 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008141
Chandler Carruth6a577462010-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 Gregor25aaff92011-10-10 14:05:31 +00008144 //
8145 // We can't exit early for !, ||, or &&, since there we have always have
8146 // 'bool' overloads.
Richard Smith958ba642013-05-05 15:51:06 +00008147 if (!HasNonRecordCandidateType &&
Douglas Gregor25aaff92011-10-10 14:05:31 +00008148 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00008149 return;
8150
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008151 // Setup an object to manage the common state for building overloads.
Richard Smith958ba642013-05-05 15:51:06 +00008152 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008153 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00008154 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008155 CandidateTypes, CandidateSet);
8156
8157 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008158 switch (Op) {
8159 case OO_None:
8160 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00008161 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008162
Chandler Carruthabb71842010-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 Blaikieb219cfc2011-09-23 05:06:16 +00008168 llvm_unreachable(
8169 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-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 Gregor74253732008-11-19 15:42:04 +00008176 break;
8177
8178 case OO_Plus: // '+' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00008179 if (Args.size() == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008180 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00008181 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00008182
8183 case OO_Minus: // '-' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00008184 if (Args.size() == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008185 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00008186 } else {
8187 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8188 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8189 }
Douglas Gregor74253732008-11-19 15:42:04 +00008190 break;
8191
Chandler Carruthabb71842010-12-12 08:51:33 +00008192 case OO_Star: // '*' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00008193 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00008194 OpBuilder.addUnaryStarPointerOverloads();
8195 else
8196 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8197 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008198
Chandler Carruthabb71842010-12-12 08:51:33 +00008199 case OO_Slash:
8200 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00008201 break;
Douglas Gregor74253732008-11-19 15:42:04 +00008202
8203 case OO_PlusPlus:
8204 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008205 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8206 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00008207 break;
8208
Douglas Gregor19b7b152009-08-24 13:43:27 +00008209 case OO_EqualEqual:
8210 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008211 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00008212 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00008213
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008214 case OO_Less:
8215 case OO_Greater:
8216 case OO_LessEqual:
8217 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00008218 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00008219 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8220 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008221
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008222 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008223 case OO_Caret:
8224 case OO_Pipe:
8225 case OO_LessLess:
8226 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008227 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008228 break;
8229
Chandler Carruthabb71842010-12-12 08:51:33 +00008230 case OO_Amp: // '&' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00008231 if (Args.size() == 1)
Chandler Carruthabb71842010-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 Gregoreb8f3062008-11-12 17:17:38 +00008244 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008245 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00008246 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008247
8248 case OO_PlusEqual:
8249 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008250 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008251 // Fall through.
8252
8253 case OO_StarEqual:
8254 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008255 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-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 Carruth3a0f3ef2010-12-12 08:11:30 +00008264 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008265 break;
8266
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008267 case OO_Exclaim:
8268 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00008269 break;
Douglas Gregor74253732008-11-19 15:42:04 +00008270
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008271 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008272 case OO_PipePipe:
8273 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008274 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008275
8276 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008277 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008278 break;
8279
8280 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008281 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008282 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00008283
8284 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00008285 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00008286 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8287 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008288 }
8289}
8290
Douglas Gregorfa047642009-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 Stump1eb44332009-09-09 15:08:12 +00008298void
Douglas Gregorfa047642009-02-04 00:32:51 +00008299Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008300 SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008301 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00008302 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008303 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00008304 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00008305 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00008306
John McCalla113e722010-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 Gregor9c6a0e92009-09-22 15:41:20 +00008314 // FIXME: Pass in the explicit template arguments?
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008315 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00008316
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00008317 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00008318 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8319 CandEnd = CandidateSet.end();
8320 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00008321 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00008322 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00008323 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00008324 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00008325 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00008326
8327 // For each of the ADL candidates we found, add it to the overload
8328 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00008329 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00008330 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00008331 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00008332 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008333 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008334
Ahmed Charles13a140c2012-02-25 11:00:22 +00008335 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8336 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008337 } else
John McCall6e266892010-01-26 03:27:55 +00008338 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00008339 FoundDecl, ExplicitTemplateArgs,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07008340 Args, CandidateSet, PartialOverloading);
Douglas Gregor364e0212009-06-27 21:05:07 +00008341 }
Douglas Gregorfa047642009-02-04 00:32:51 +00008342}
8343
Douglas Gregor8e9bebd2008-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).
Stephen Hines176edba2014-12-01 14:53:08 -08008346bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8347 const OverloadCandidate &Cand2,
8348 SourceLocation Loc,
8349 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-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 Gregor88a35142008-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 Gregor8e9bebd2008-10-21 16:13:35 +00008366
Douglas Gregor3e15cc32009-07-07 23:38:56 +00008367 // C++ [over.match.best]p1:
Mike Stump1eb44332009-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 Gregor3e15cc32009-07-07 23:38:56 +00008370 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008371 unsigned NumArgs = Cand1.NumConversions;
8372 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008373 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00008374 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00008375 switch (CompareImplicitConversionSequences(S,
8376 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +00008393 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00008394 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008395 if (HasBetterConversion)
8396 return true;
8397
Douglas Gregorf1991ea2008-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 Gregor8fcc5162010-09-12 08:07:23 +00008404 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00008405 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008406 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-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.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008411 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);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008417
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008418 if (Result != ImplicitConversionSequence::Indistinguishable)
8419 return Result == ImplicitConversionSequence::Better;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008420
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008421 // 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 Gregorf1991ea2008-11-07 22:36:19 +00008449 }
8450
Stephen Hines651f13c2014-04-23 16:59:28 -07008451 // 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;
Stephen Hines651f13c2014-04-23 16:59:28 -07008459 if (Cand1.Function->hasAttrs()) {
8460 Cand1Attrs = Cand1.Function->getAttrs();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008461 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8462 IsNotEnableIfAttr),
8463 Cand1Attrs.end());
8464 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
Stephen Hines651f13c2014-04-23 16:59:28 -07008465 }
8466
8467 AttrVec Cand2Attrs;
Stephen Hines651f13c2014-04-23 16:59:28 -07008468 if (Cand2.Function->hasAttrs()) {
8469 Cand2Attrs = Cand2.Function->getAttrs();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008470 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8471 IsNotEnableIfAttr),
8472 Cand2Attrs.end());
8473 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
Stephen Hines651f13c2014-04-23 16:59:28 -07008474 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008475
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++;
Stephen Hines651f13c2014-04-23 16:59:28 -07008484 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008485 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8486 S.getASTContext(), true);
8487 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8488 S.getASTContext(), true);
Stephen Hines651f13c2014-04-23 16:59:28 -07008489 if (Cand1ID != Cand2ID)
8490 return false;
8491 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008492
8493 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07008494 }
8495
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008496 return false;
8497}
8498
Mike Stump1eb44332009-09-09 15:08:12 +00008499/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00008500/// within an overload candidate set.
8501///
James Dennettefce31f2012-06-22 08:10:18 +00008502/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00008503/// which overload resolution occurs.
8504///
James Dennettefce31f2012-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 Gregore0762c92009-06-19 23:52:42 +00008507///
8508/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00008509OverloadingResult
8510OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00008511 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00008512 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008513 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00008514 Best = end();
8515 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8516 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008517 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008518 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008519 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008520 }
8521
8522 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00008523 if (Best == end())
Douglas Gregor8e9bebd2008-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 McCall120d63c2010-08-24 20:38:10 +00008528 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00008529 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008530 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008531 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008532 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00008533 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008534 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008535 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008536 }
Mike Stump1eb44332009-09-09 15:08:12 +00008537
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008538 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008539 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008540 (Best->Function->isDeleted() ||
8541 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008542 return OR_Deleted;
8543
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008544 return OR_Success;
8545}
8546
John McCall3c80f572010-01-12 02:15:36 +00008547namespace {
8548
8549enum OverloadCandidateKind {
8550 oc_function,
8551 oc_method,
8552 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00008553 oc_function_template,
8554 oc_method_template,
8555 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00008556 oc_implicit_default_constructor,
8557 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00008558 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008559 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00008560 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008561 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00008562};
8563
John McCall220ccbf2010-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 McCallb1622a12010-01-06 09:43:14 +00008574
8575 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00008576 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008577 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008578
Sebastian Redlf677ea32011-02-05 19:23:19 +00008579 if (Ctor->getInheritedConstructor())
8580 return oc_implicit_inherited_constructor;
8581
Sean Hunt82713172011-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 McCallb1622a12010-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 McCall3c80f572010-01-12 02:15:36 +00008596 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008597 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008598
Sean Hunt82713172011-05-25 23:16:36 +00008599 if (Meth->isMoveAssignmentOperator())
8600 return oc_implicit_move_assignment;
8601
Douglas Gregoref7d78b2012-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 McCall3c80f572010-01-12 02:15:36 +00008607 }
8608
John McCall220ccbf2010-01-13 00:25:19 +00008609 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008610}
8611
Larisse Voufo43847122013-07-19 23:00:19 +00008612void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redlf677ea32011-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 McCall3c80f572010-01-12 02:15:36 +00008622} // end anonymous namespace
8623
8624// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008625void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008626 std::string FnDesc;
8627 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-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 Redlf677ea32011-02-05 19:23:19 +00008632 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008633}
8634
Nick Lewycky199e3702013-09-22 10:06:01 +00008635// Notes the location of all overload candidates designated through
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008636// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008637void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-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 Trieu6efd4c52011-11-23 22:32:32 +00008648 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008649 } else if (FunctionDecl *Fun
8650 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008651 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008652 }
8653 }
8654}
8655
John McCall1d318332010-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 McCall120d63c2010-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-Gay45a37da2012-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 McCall120d63c2010-08-24 20:38:10 +00008675 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008676 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008677 if (I != E)
8678 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008679}
8680
Stephen Hines176edba2014-12-01 14:53:08 -08008681static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8682 unsigned I) {
John McCalladbb8f82010-01-13 09:16:55 +00008683 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8684 assert(Conv.isBad());
John McCall220ccbf2010-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 McCalladbb8f82010-01-13 09:16:55 +00008691 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008692 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008693 if (I == 0)
8694 isObjectArgument = true;
8695 else
8696 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008697 }
8698
John McCall220ccbf2010-01-13 00:25:19 +00008699 std::string FnDesc;
8700 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8701
John McCalladbb8f82010-01-13 09:16:55 +00008702 Expr *FromExpr = Conv.Bad.FromExpr;
8703 QualType FromTy = Conv.Bad.getFromType();
8704 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008705
John McCall5920dbb2010-02-02 02:42:52 +00008706 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008707 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008708 Expr *E = FromExpr->IgnoreParens();
8709 if (isa<UnaryOperator>(E))
8710 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008711 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-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 Redlf677ea32011-02-05 19:23:19 +00008717 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008718 return;
8719 }
8720
John McCall258b2032010-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 McCall651f3ee2010-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 McCall651f3ee2010-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 Redlf677ea32011-02-05 19:23:19 +00008746 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008747 return;
8748 }
8749
John McCallf85e1932011-06-15 23:02:42 +00008750 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008751 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-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 Gregor028ea4b2011-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 McCall651f3ee2010-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 Redlf677ea32011-02-05 19:23:19 +00008786 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008787 return;
8788 }
8789
Sebastian Redlfd2a00a2011-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 McCall258b2032010-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 Redlf677ea32011-02-05 19:23:19 +00008812 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008813 return;
8814 }
8815
Douglas Gregor85789812010-06-30 23:01:39 +00008816 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008817 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-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 Takumidfbb02a2011-01-27 07:10:08 +00008824 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008825 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008826 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-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 Gregor2f9d8742010-07-01 02:14:45 +00008837 BaseToDerivedConversion = 2;
8838 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-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 Uhrain0d3317e2012-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 Gregor2f9d8742010-07-01 02:14:45 +00008853 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008854 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008855
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008856 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008857 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008858 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008859 << (unsigned) FnKind << FnDesc
8860 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008861 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008862 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008863 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008864 return;
8865 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008866
Fariborz Jahanian909bcb32011-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 Zaksb89fe6b2011-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 McCalladbb8f82010-01-13 09:16:55 +00008884 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-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 Kramer1136ef02012-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 Zaksb89fe6b2011-07-19 19:49:12 +00008891 FDiag << *HI;
8892 S.Diag(Fn->getLocation(), FDiag);
8893
Sebastian Redlf677ea32011-02-05 19:23:19 +00008894 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008895}
8896
Larisse Voufo43847122013-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.
Stephen Hines176edba2014-12-01 14:53:08 -08008900static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8901 unsigned NumArgs) {
John McCalladbb8f82010-01-13 09:16:55 +00008902 FunctionDecl *Fn = Cand->Function;
John McCalladbb8f82010-01-13 09:16:55 +00008903 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008904
Douglas Gregor439d3c32011-05-05 00:13:13 +00008905 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo43847122013-07-19 23:00:19 +00008906 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor439d3c32011-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 Voufo43847122013-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.
Stephen Hines176edba2014-12-01 14:53:08 -08008928static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo43847122013-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 Gregor439d3c32011-05-05 00:13:13 +00008939
John McCalladbb8f82010-01-13 09:16:55 +00008940 // at least / at most / exactly
8941 unsigned mode, modeCount;
8942 if (NumFormalArgs < MinParams) {
Stephen Hines651f13c2014-04-23 16:59:28 -07008943 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8944 FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008945 mode = 0; // "at least"
8946 else
8947 mode = 2; // "exactly"
8948 modeCount = MinParams;
8949 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07008950 if (MinParams != FnTy->getNumParams())
John McCalladbb8f82010-01-13 09:16:55 +00008951 mode = 1; // "at most"
8952 else
8953 mode = 2; // "exactly"
Stephen Hines651f13c2014-04-23 16:59:28 -07008954 modeCount = FnTy->getNumParams();
John McCalladbb8f82010-01-13 09:16:55 +00008955 }
8956
8957 std::string Description;
8958 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8959
Richard Smithf7b80562012-05-11 05:16:41 +00008960 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8961 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008962 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8963 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smithf7b80562012-05-11 05:16:41 +00008964 else
8965 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008966 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8967 << mode << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008968 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008969}
8970
Larisse Voufo43847122013-07-19 23:00:19 +00008971/// Arity mismatch diagnosis specific to a function overload candidate.
Stephen Hines176edba2014-12-01 14:53:08 -08008972static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8973 unsigned NumFormalArgs) {
Larisse Voufo43847122013-07-19 23:00:19 +00008974 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8975 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8976}
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008977
Stephen Hines176edba2014-12-01 14:53:08 -08008978static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo43847122013-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.
Stephen Hines176edba2014-12-01 14:53:08 -08008989static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8990 DeductionFailureInfo &DeductionFailure,
8991 unsigned NumArgs) {
Larisse Voufo43847122013-07-19 23:00:19 +00008992 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-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 Voufo43847122013-07-19 23:00:19 +00008997 switch (DeductionFailure.Result) {
John McCall342fec42010-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 McCall342fec42010-02-01 18:53:26 +00009002 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo43847122013-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 McCall342fec42010-02-01 18:53:26 +00009007 return;
9008 }
9009
John McCall57e97782010-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 Voufo43847122013-07-19 23:00:19 +00009014 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall57e97782010-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 McCall49f4e1c2010-12-10 11:01:00 +00009018 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00009019 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00009020 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-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 Voufo43847122013-07-19 23:00:19 +00009027 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall57e97782010-08-05 09:05:08 +00009028
Larisse Voufo43847122013-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 McCall57e97782010-08-05 09:05:08 +00009032 return;
9033 }
9034
9035 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00009036 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00009037 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00009038 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00009039 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00009040 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00009041 which = 1;
9042 else {
Douglas Gregora9333192010-05-08 17:41:32 +00009043 which = 2;
9044 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009045
Larisse Voufo43847122013-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 Gregora9333192010-05-08 17:41:32 +00009051 return;
9052 }
Douglas Gregora18592e2010-05-08 18:13:28 +00009053
Douglas Gregorf1a84452010-05-08 19:15:54 +00009054 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009055 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00009056 if (ParamD->getDeclName())
Larisse Voufo43847122013-07-19 23:00:19 +00009057 S.Diag(Templated->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00009058 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo43847122013-07-19 23:00:19 +00009059 << ParamD->getDeclName();
Douglas Gregorf1a84452010-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 Voufo43847122013-07-19 23:00:19 +00009069 S.Diag(Templated->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00009070 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo43847122013-07-19 23:00:19 +00009071 << (index + 1);
Douglas Gregorf1a84452010-05-08 19:15:54 +00009072 }
Larisse Voufo43847122013-07-19 23:00:19 +00009073 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorf1a84452010-05-08 19:15:54 +00009074 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009075
Douglas Gregora18592e2010-05-08 18:13:28 +00009076 case Sema::TDK_TooManyArguments:
9077 case Sema::TDK_TooFewArguments:
Larisse Voufo43847122013-07-19 23:00:19 +00009078 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregora18592e2010-05-08 18:13:28 +00009079 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00009080
9081 case Sema::TDK_InstantiationDepth:
Larisse Voufo43847122013-07-19 23:00:19 +00009082 S.Diag(Templated->getLocation(),
9083 diag::note_ovl_candidate_instantiation_depth);
9084 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorec20f462010-05-08 20:07:26 +00009085 return;
9086
9087 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00009088 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009089 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00009090 if (TemplateArgumentList *Args =
Larisse Voufo43847122013-07-19 23:00:19 +00009091 DeductionFailure.getTemplateArgumentList()) {
Richard Smithb8590f32012-05-07 09:03:25 +00009092 TemplateArgString = " ";
9093 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo43847122013-07-19 23:00:19 +00009094 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smithb8590f32012-05-07 09:03:25 +00009095 }
9096
Richard Smith4493c0a2012-05-09 05:17:00 +00009097 // If this candidate was disabled by enable_if, say so.
Larisse Voufo43847122013-07-19 23:00:19 +00009098 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith4493c0a2012-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 Smithb8590f32012-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 Gribenkocfa88f82013-01-12 19:30:44 +00009111 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00009112 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00009113 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00009114 SFINAEArgString = ": ";
9115 R = SourceRange(PDiag->first, PDiag->first);
9116 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9117 }
9118
Larisse Voufo43847122013-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 Gregorec20f462010-05-08 20:07:26 +00009123 return;
9124 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009125
Richard Smith0efa62f2013-01-31 04:03:12 +00009126 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo43847122013-07-19 23:00:19 +00009127 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9128 S.Diag(Templated->getLocation(),
Richard Smith0efa62f2013-01-31 04:03:12 +00009129 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo43847122013-07-19 23:00:19 +00009130 << R.Expression->getName();
Richard Smith0efa62f2013-01-31 04:03:12 +00009131 return;
9132 }
9133
Richard Trieueef35f82013-04-08 21:11:40 +00009134 case Sema::TDK_NonDeducedMismatch: {
Richard Smith29805ca2013-01-31 05:19:49 +00009135 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo43847122013-07-19 23:00:19 +00009136 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9137 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieueef35f82013-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 Voufo43847122013-07-19 23:00:19 +00009152 S.Diag(Templated->getLocation(),
Richard Trieueef35f82013-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 Valifad9e132013-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 Voufo43847122013-07-19 23:00:19 +00009163 S.Diag(Templated->getLocation(),
9164 diag::note_ovl_candidate_non_deduced_mismatch)
9165 << FirstTA << SecondTA;
Richard Smith29805ca2013-01-31 05:19:49 +00009166 return;
Richard Trieueef35f82013-04-08 21:11:40 +00009167 }
John McCall342fec42010-02-01 18:53:26 +00009168 // TODO: diagnose these individually, then kill off
9169 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00009170 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo43847122013-07-19 23:00:19 +00009171 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9172 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall342fec42010-02-01 18:53:26 +00009173 return;
9174 }
9175}
9176
Larisse Voufo43847122013-07-19 23:00:19 +00009177/// Diagnose a failed template-argument deduction, for function calls.
Stephen Hines176edba2014-12-01 14:53:08 -08009178static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9179 unsigned NumArgs) {
Larisse Voufo43847122013-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 Collingbourne78dd67e2011-10-02 23:49:40 +00009189/// CUDA: diagnose an invalid call across targets.
Stephen Hines176edba2014-12-01 14:53:08 -08009190static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne78dd67e2011-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)
Stephen Hines176edba2014-12-01 14:53:08 -08009201 << (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 Collingbourne78dd67e2011-10-02 23:49:40 +00009242}
9243
Stephen Hines176edba2014-12-01 14:53:08 -08009244static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Stephen Hines651f13c2014-04-23 16:59:28 -07009245 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 McCall342fec42010-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.
Stephen Hines176edba2014-12-01 14:53:08 -08009266static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9267 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00009268 FunctionDecl *Fn = Cand->Function;
9269
John McCall81201622010-01-08 04:41:39 +00009270 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00009271 if (Cand->Viable && (Fn->isDeleted() ||
9272 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00009273 std::string FnDesc;
9274 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00009275
9276 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00009277 << FnKind << FnDesc
9278 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00009279 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00009280 return;
John McCall81201622010-01-08 04:41:39 +00009281 }
9282
John McCall220ccbf2010-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 McCall1d318332010-01-12 00:44:57 +00009288
John McCalladbb8f82010-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 McCall220ccbf2010-01-13 00:25:19 +00009293
John McCalladbb8f82010-01-13 09:16:55 +00009294 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00009295 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00009296
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009297 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 McCall717e8912010-01-23 05:17:32 +00009304 case ovl_fail_trivial_conversion:
9305 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00009306 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00009307 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00009308
John McCallb1bdc622010-02-25 01:37:24 +00009309 case ovl_fail_bad_conversion: {
9310 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009311 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00009312 if (Cand->Conversions[I].isBad())
9313 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009314
John McCalladbb8f82010-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 McCall220ccbf2010-01-13 00:25:19 +00009319 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009320
9321 case ovl_fail_bad_target:
9322 return DiagnoseBadTarget(S, Cand);
Stephen Hines651f13c2014-04-23 16:59:28 -07009323
9324 case ovl_fail_enable_if:
9325 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00009326 }
John McCalla1d7d622010-01-08 00:58:21 +00009327}
9328
Stephen Hines176edba2014-12-01 14:53:08 -08009329static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalla1d7d622010-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 Redlf677ea32011-02-05 19:23:19 +00009359 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00009360}
9361
Stephen Hines176edba2014-12-01 14:53:08 -08009362static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9363 SourceLocation OpLoc,
9364 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009365 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00009366 std::string TypeStr("operator");
9367 TypeStr += Opc;
9368 TypeStr += "(";
9369 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009370 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-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
Stephen Hines176edba2014-12-01 14:53:08 -08009381static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9382 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009383 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00009384 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9385 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00009386 if (ICS.isBad()) break; // all meaningless after first invalid
9387 if (!ICS.isAmbiguous()) continue;
9388
John McCall120d63c2010-08-24 20:38:10 +00009389 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00009390 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00009391 }
9392}
9393
Larisse Voufo43847122013-07-19 23:00:19 +00009394static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall1b77e732010-01-15 23:32:50 +00009395 if (Cand->Function)
9396 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00009397 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00009398 return Cand->Surrogate->getLocation();
9399 return SourceLocation();
9400}
9401
Larisse Voufo43847122013-07-19 23:00:19 +00009402static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00009403 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00009404 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00009405 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00009406
Douglas Gregorae19fbb2012-09-13 21:01:57 +00009407 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-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 Smith29805ca2013-01-31 05:19:49 +00009417 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-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 Kramerafc5b152011-09-10 21:52:04 +00009431 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00009432}
9433
Stephen Hines176edba2014-12-01 14:53:08 -08009434namespace {
John McCallbf65c0b2010-01-12 00:48:53 +00009435struct CompareOverloadCandidatesForDisplay {
9436 Sema &S;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009437 size_t NumArgs;
9438
9439 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9440 : S(S), NumArgs(nArgs) {}
John McCall81201622010-01-08 04:41:39 +00009441
9442 bool operator()(const OverloadCandidate *L,
9443 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00009444 // Fast-path this check.
9445 if (L == R) return false;
9446
John McCall81201622010-01-08 04:41:39 +00009447 // Order first by viability.
John McCallbf65c0b2010-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 McCall120d63c2010-08-24 20:38:10 +00009454 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9455 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00009456 } else if (R->Viable)
9457 return false;
John McCall81201622010-01-08 04:41:39 +00009458
John McCall1b77e732010-01-15 23:32:50 +00009459 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00009460
John McCall1b77e732010-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 ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009465 L->FailureKind == ovl_fail_too_few_arguments) {
9466 if (R->FailureKind == ovl_fail_too_many_arguments ||
9467 R->FailureKind == ovl_fail_too_few_arguments) {
9468 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 }
9479 return LDist < RDist;
9480 }
John McCall1b77e732010-01-15 23:32:50 +00009481 return false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009482 }
John McCall1b77e732010-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 McCall81201622010-01-08 04:41:39 +00009486
John McCall717e8912010-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 Zaksb89fe6b2011-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 Zaksffe9edd2011-07-21 00:34:39 +00009499 if (numLFixes != numRFixes) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07009500 return numLFixes < numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00009501 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009502
John McCall717e8912010-01-23 05:17:32 +00009503 // If there's any ordering between the defined conversions...
9504 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009505 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00009506
9507 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00009508 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009509 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00009510 switch (CompareImplicitConversionSequences(S,
9511 L->Conversions[I],
9512 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00009513 case ImplicitConversionSequence::Better:
9514 leftBetter++;
9515 break;
9516
9517 case ImplicitConversionSequence::Worse:
9518 leftBetter--;
9519 break;
9520
9521 case ImplicitConversionSequence::Indistinguishable:
9522 break;
9523 }
9524 }
9525 if (leftBetter > 0) return true;
9526 if (leftBetter < 0) return false;
9527
9528 } else if (R->FailureKind == ovl_fail_bad_conversion)
9529 return false;
9530
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00009531 if (L->FailureKind == ovl_fail_bad_deduction) {
9532 if (R->FailureKind != ovl_fail_bad_deduction)
9533 return true;
9534
9535 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9536 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00009537 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00009538 } else if (R->FailureKind == ovl_fail_bad_deduction)
9539 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00009540
John McCall1b77e732010-01-15 23:32:50 +00009541 // TODO: others?
9542 }
9543
9544 // Sort everything else by location.
9545 SourceLocation LLoc = GetLocationForCandidate(L);
9546 SourceLocation RLoc = GetLocationForCandidate(R);
9547
9548 // Put candidates without locations (e.g. builtins) at the end.
9549 if (LLoc.isInvalid()) return false;
9550 if (RLoc.isInvalid()) return true;
9551
9552 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00009553 }
9554};
Stephen Hines176edba2014-12-01 14:53:08 -08009555}
John McCall81201622010-01-08 04:41:39 +00009556
John McCall717e8912010-01-23 05:17:32 +00009557/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009558/// computes up to the first. Produces the FixIt set if possible.
Stephen Hines176edba2014-12-01 14:53:08 -08009559static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9560 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00009561 assert(!Cand->Viable);
9562
9563 // Don't do anything on failures other than bad conversion.
9564 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9565
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009566 // We only want the FixIts if all the arguments can be corrected.
9567 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00009568 // Use a implicit copy initialization to check conversion fixes.
9569 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009570
John McCall717e8912010-01-23 05:17:32 +00009571 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00009572 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009573 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00009574 while (true) {
9575 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9576 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009577 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00009578 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00009579 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009580 }
John McCall717e8912010-01-23 05:17:32 +00009581 }
9582
9583 if (ConvIdx == ConvCount)
9584 return;
9585
John McCallb1bdc622010-02-25 01:37:24 +00009586 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9587 "remaining conversion is initialized?");
9588
Douglas Gregor23ef6c02010-04-16 17:45:54 +00009589 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00009590 // operation somehow.
9591 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00009592
9593 const FunctionProtoType* Proto;
9594 unsigned ArgIdx = ConvIdx;
9595
9596 if (Cand->IsSurrogate) {
9597 QualType ConvType
9598 = Cand->Surrogate->getConversionType().getNonReferenceType();
9599 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9600 ConvType = ConvPtrType->getPointeeType();
9601 Proto = ConvType->getAs<FunctionProtoType>();
9602 ArgIdx--;
9603 } else if (Cand->Function) {
9604 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9605 if (isa<CXXMethodDecl>(Cand->Function) &&
9606 !isa<CXXConstructorDecl>(Cand->Function))
9607 ArgIdx--;
9608 } else {
9609 // Builtin binary operator with a bad first conversion.
9610 assert(ConvCount <= 3);
9611 for (; ConvIdx != ConvCount; ++ConvIdx)
9612 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009613 = TryCopyInitialization(S, Args[ConvIdx],
9614 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009615 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009616 /*InOverloadResolution*/ true,
9617 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009618 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00009619 return;
9620 }
9621
9622 // Fill in the rest of the conversions.
Stephen Hines651f13c2014-04-23 16:59:28 -07009623 unsigned NumParams = Proto->getNumParams();
John McCall717e8912010-01-23 05:17:32 +00009624 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Stephen Hines651f13c2014-04-23 16:59:28 -07009625 if (ArgIdx < NumParams) {
9626 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9627 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9628 /*InOverloadResolution=*/true,
9629 /*AllowObjCWritebackConversion=*/
9630 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009631 // Store the FixIt in the candidate if it exists.
9632 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00009633 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009634 }
John McCall717e8912010-01-23 05:17:32 +00009635 else
9636 Cand->Conversions[ConvIdx].setEllipsis();
9637 }
9638}
9639
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009640/// PrintOverloadCandidates - When overload resolution fails, prints
9641/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00009642/// set.
John McCall120d63c2010-08-24 20:38:10 +00009643void OverloadCandidateSet::NoteCandidates(Sema &S,
9644 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009645 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00009646 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00009647 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00009648 // Sort the candidates by viability and position. Sorting directly would
9649 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009650 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00009651 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9652 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00009653 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00009654 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00009655 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00009656 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009657 if (Cand->Function || Cand->IsSurrogate)
9658 Cands.push_back(Cand);
9659 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9660 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00009661 }
9662 }
9663
John McCallbf65c0b2010-01-12 00:48:53 +00009664 std::sort(Cands.begin(), Cands.end(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009665 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009666
John McCall1d318332010-01-12 00:44:57 +00009667 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00009668
Chris Lattner5f9e2722011-07-23 10:55:15 +00009669 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00009670 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009671 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00009672 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9673 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00009674
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009675 // Set an arbitrary limit on the number of candidate functions we'll spam
9676 // the user with. FIXME: This limit should depend on details of the
9677 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00009678 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009679 break;
9680 }
9681 ++CandsShown;
9682
John McCalla1d7d622010-01-08 00:58:21 +00009683 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009684 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00009685 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00009686 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009687 else {
9688 assert(Cand->Viable &&
9689 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00009690 // Generally we only see ambiguities including viable builtin
9691 // operators if overload resolution got screwed up by an
9692 // ambiguous user-defined conversion.
9693 //
9694 // FIXME: It's quite possible for different conversions to see
9695 // different ambiguities, though.
9696 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00009697 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00009698 ReportedAmbiguousConversions = true;
9699 }
John McCalla1d7d622010-01-08 00:58:21 +00009700
John McCall1d318332010-01-12 00:44:57 +00009701 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00009702 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00009703 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009704 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009705
9706 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00009707 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009708}
9709
Larisse Voufo43847122013-07-19 23:00:19 +00009710static SourceLocation
9711GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9712 return Cand->Specialization ? Cand->Specialization->getLocation()
9713 : SourceLocation();
9714}
9715
Stephen Hines176edba2014-12-01 14:53:08 -08009716namespace {
Larisse Voufo43847122013-07-19 23:00:19 +00009717struct CompareTemplateSpecCandidatesForDisplay {
9718 Sema &S;
9719 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9720
9721 bool operator()(const TemplateSpecCandidate *L,
9722 const TemplateSpecCandidate *R) {
9723 // Fast-path this check.
9724 if (L == R)
9725 return false;
9726
9727 // Assuming that both candidates are not matches...
9728
9729 // Sort by the ranking of deduction failures.
9730 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9731 return RankDeductionFailure(L->DeductionFailure) <
9732 RankDeductionFailure(R->DeductionFailure);
9733
9734 // Sort everything else by location.
9735 SourceLocation LLoc = GetLocationForCandidate(L);
9736 SourceLocation RLoc = GetLocationForCandidate(R);
9737
9738 // Put candidates without locations (e.g. builtins) at the end.
9739 if (LLoc.isInvalid())
9740 return false;
9741 if (RLoc.isInvalid())
9742 return true;
9743
9744 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9745 }
9746};
Stephen Hines176edba2014-12-01 14:53:08 -08009747}
Larisse Voufo43847122013-07-19 23:00:19 +00009748
9749/// Diagnose a template argument deduction failure.
9750/// We are treating these failures as overload failures due to bad
9751/// deductions.
9752void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9753 DiagnoseBadDeduction(S, Specialization, // pattern
9754 DeductionFailure, /*NumArgs=*/0);
9755}
9756
9757void TemplateSpecCandidateSet::destroyCandidates() {
9758 for (iterator i = begin(), e = end(); i != e; ++i) {
9759 i->DeductionFailure.Destroy();
9760 }
9761}
9762
9763void TemplateSpecCandidateSet::clear() {
9764 destroyCandidates();
9765 Candidates.clear();
9766}
9767
9768/// NoteCandidates - When no template specialization match is found, prints
9769/// diagnostic messages containing the non-matching specializations that form
9770/// the candidate set.
9771/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9772/// OCD == OCD_AllCandidates and Cand->Viable == false.
9773void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9774 // Sort the candidates by position (assuming no candidate is a match).
9775 // Sorting directly would be prohibitive, so we make a set of pointers
9776 // and sort those.
9777 SmallVector<TemplateSpecCandidate *, 32> Cands;
9778 Cands.reserve(size());
9779 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9780 if (Cand->Specialization)
9781 Cands.push_back(Cand);
Stephen Hines651f13c2014-04-23 16:59:28 -07009782 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo43847122013-07-19 23:00:19 +00009783 // in general, want to list every possible builtin candidate.
9784 }
9785
9786 std::sort(Cands.begin(), Cands.end(),
9787 CompareTemplateSpecCandidatesForDisplay(S));
9788
9789 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9790 // for generalization purposes (?).
9791 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9792
9793 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9794 unsigned CandsShown = 0;
9795 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9796 TemplateSpecCandidate *Cand = *I;
9797
9798 // Set an arbitrary limit on the number of candidates we'll spam
9799 // the user with. FIXME: This limit should depend on details of the
9800 // candidate list.
9801 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9802 break;
9803 ++CandsShown;
9804
9805 assert(Cand->Specialization &&
9806 "Non-matching built-in candidates are not added to Cands.");
9807 Cand->NoteDeductionFailure(S);
9808 }
9809
9810 if (I != E)
9811 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9812}
9813
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009814// [PossiblyAFunctionType] --> [Return]
9815// NonFunctionType --> NonFunctionType
9816// R (A) --> R(A)
9817// R (*)(A) --> R (A)
9818// R (&)(A) --> R (A)
9819// R (S::*)(A) --> R (A)
9820QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9821 QualType Ret = PossiblyAFunctionType;
9822 if (const PointerType *ToTypePtr =
9823 PossiblyAFunctionType->getAs<PointerType>())
9824 Ret = ToTypePtr->getPointeeType();
9825 else if (const ReferenceType *ToTypeRef =
9826 PossiblyAFunctionType->getAs<ReferenceType>())
9827 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00009828 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009829 PossiblyAFunctionType->getAs<MemberPointerType>())
9830 Ret = MemTypePtr->getPointeeType();
9831 Ret =
9832 Context.getCanonicalType(Ret).getUnqualifiedType();
9833 return Ret;
9834}
Douglas Gregor904eed32008-11-10 20:40:00 +00009835
Stephen Hines176edba2014-12-01 14:53:08 -08009836namespace {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009837// A helper class to help with address of function resolution
9838// - allows us to avoid passing around all those ugly parameters
Stephen Hines176edba2014-12-01 14:53:08 -08009839class AddressOfFunctionResolver {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009840 Sema& S;
9841 Expr* SourceExpr;
9842 const QualType& TargetType;
9843 QualType TargetFunctionType; // Extracted function type from target type
9844
9845 bool Complain;
9846 //DeclAccessPair& ResultFunctionAccessPair;
9847 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009848
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009849 bool TargetTypeIsNonStaticMemberFunction;
9850 bool FoundNonTemplateFunction;
David Majnemer576a9af2013-08-01 06:13:59 +00009851 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009852
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009853 OverloadExpr::FindResult OvlExprInfo;
9854 OverloadExpr *OvlExpr;
9855 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009856 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo43847122013-07-19 23:00:19 +00009857 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009858
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009859public:
Larisse Voufo43847122013-07-19 23:00:19 +00009860 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9861 const QualType &TargetType, bool Complain)
9862 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9863 Complain(Complain), Context(S.getASTContext()),
9864 TargetTypeIsNonStaticMemberFunction(
9865 !!TargetType->getAs<MemberPointerType>()),
9866 FoundNonTemplateFunction(false),
David Majnemer576a9af2013-08-01 06:13:59 +00009867 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo43847122013-07-19 23:00:19 +00009868 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9869 OvlExpr(OvlExprInfo.Expression),
9870 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009871 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruth90434232011-03-29 08:08:18 +00009872
David Majnemer576a9af2013-08-01 06:13:59 +00009873 if (TargetFunctionType->isFunctionType()) {
9874 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9875 if (!UME->isImplicitAccess() &&
9876 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9877 StaticMemberFunctionFromBoundPointer = true;
9878 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9879 DeclAccessPair dap;
9880 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9881 OvlExpr, false, &dap)) {
9882 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9883 if (!Method->isStatic()) {
9884 // If the target type is a non-function type and the function found
9885 // is a non-static member function, pretend as if that was the
9886 // target, it's the only possible type to end up with.
9887 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruth90434232011-03-29 08:08:18 +00009888
David Majnemer576a9af2013-08-01 06:13:59 +00009889 // And skip adding the function if its not in the proper form.
9890 // We'll diagnose this due to an empty set of functions.
9891 if (!OvlExprInfo.HasFormOfMemberPointer)
9892 return;
Chandler Carruth90434232011-03-29 08:08:18 +00009893 }
9894
David Majnemer576a9af2013-08-01 06:13:59 +00009895 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor83314aa2009-07-08 20:55:45 +00009896 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009897 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009898 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009899
9900 if (OvlExpr->hasExplicitTemplateArgs())
9901 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009902
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009903 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9904 // C++ [over.over]p4:
9905 // If more than one function is selected, [...]
9906 if (Matches.size() > 1) {
9907 if (FoundNonTemplateFunction)
9908 EliminateAllTemplateMatches();
9909 else
9910 EliminateAllExceptMostSpecializedTemplate();
9911 }
9912 }
9913 }
9914
9915private:
9916 bool isTargetTypeAFunction() const {
9917 return TargetFunctionType->isFunctionType();
9918 }
9919
9920 // [ToType] [Return]
9921
9922 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9923 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9924 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9925 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9926 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9927 }
9928
9929 // return true if any matching specializations were found
9930 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9931 const DeclAccessPair& CurAccessFunPair) {
9932 if (CXXMethodDecl *Method
9933 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9934 // Skip non-static function templates when converting to pointer, and
9935 // static when converting to member pointer.
9936 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9937 return false;
9938 }
9939 else if (TargetTypeIsNonStaticMemberFunction)
9940 return false;
9941
9942 // C++ [over.over]p2:
9943 // If the name is a function template, template argument deduction is
9944 // done (14.8.2.2), and if the argument deduction succeeds, the
9945 // resulting template argument list is used to generate a single
9946 // function template specialization, which is added to the set of
9947 // overloaded functions considered.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009948 FunctionDecl *Specialization = nullptr;
Larisse Voufo43847122013-07-19 23:00:19 +00009949 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009950 if (Sema::TemplateDeductionResult Result
9951 = S.DeduceTemplateArguments(FunctionTemplate,
9952 &OvlExplicitTemplateArgs,
9953 TargetFunctionType, Specialization,
Douglas Gregor092140a2013-04-17 08:45:07 +00009954 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo43847122013-07-19 23:00:19 +00009955 // Make a note of the failed deduction for diagnostics.
9956 FailedCandidates.addCandidate()
9957 .set(FunctionTemplate->getTemplatedDecl(),
9958 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009959 return false;
9960 }
9961
Douglas Gregor092140a2013-04-17 08:45:07 +00009962 // Template argument deduction ensures that we have an exact match or
9963 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009964 // This function template specicalization works.
9965 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor092140a2013-04-17 08:45:07 +00009966 assert(S.isSameOrCompatibleFunctionType(
9967 Context.getCanonicalType(Specialization->getType()),
9968 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009969 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9970 return true;
9971 }
9972
9973 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9974 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009975 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009976 // Skip non-static functions when converting to pointer, and static
9977 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009978 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9979 return false;
9980 }
9981 else if (TargetTypeIsNonStaticMemberFunction)
9982 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009983
Chandler Carruthbd647292009-12-29 06:17:27 +00009984 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009985 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009986 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Stephen Hines176edba2014-12-01 14:53:08 -08009987 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009988 return false;
9989
Richard Smith60e141e2013-05-04 07:00:32 +00009990 // If any candidate has a placeholder return type, trigger its deduction
9991 // now.
Stephen Hines176edba2014-12-01 14:53:08 -08009992 if (S.getLangOpts().CPlusPlus14 &&
Stephen Hines651f13c2014-04-23 16:59:28 -07009993 FunDecl->getReturnType()->isUndeducedType() &&
Richard Smith60e141e2013-05-04 07:00:32 +00009994 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9995 return false;
9996
Douglas Gregor43c79c22009-12-09 00:47:37 +00009997 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009998 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9999 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +000010000 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
10001 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010002 Matches.push_back(std::make_pair(CurAccessFunPair,
10003 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +000010004 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010005 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +000010006 }
Mike Stump1eb44332009-09-09 15:08:12 +000010007 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010008
10009 return false;
10010 }
10011
10012 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10013 bool Ret = false;
10014
10015 // If the overload expression doesn't have the form of a pointer to
10016 // member, don't try to convert it to a pointer-to-member type.
10017 if (IsInvalidFormOfPointerToMemberFunction())
10018 return false;
10019
10020 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10021 E = OvlExpr->decls_end();
10022 I != E; ++I) {
10023 // Look through any using declarations to find the underlying function.
10024 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10025
10026 // C++ [over.over]p3:
10027 // Non-member functions and static member functions match
10028 // targets of type "pointer-to-function" or "reference-to-function."
10029 // Nonstatic member functions match targets of
10030 // type "pointer-to-member-function."
10031 // Note that according to DR 247, the containing class does not matter.
10032 if (FunctionTemplateDecl *FunctionTemplate
10033 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10034 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10035 Ret = true;
10036 }
10037 // If we have explicit template arguments supplied, skip non-templates.
10038 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10039 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10040 Ret = true;
10041 }
10042 assert(Ret || Matches.empty());
10043 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +000010044 }
10045
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010046 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010047 // [...] and any given function template specialization F1 is
10048 // eliminated if the set contains a second function template
10049 // specialization whose function template is more specialized
10050 // than the function template of F1 according to the partial
10051 // ordering rules of 14.5.5.2.
10052
10053 // The algorithm specified above is quadratic. We instead use a
10054 // two-pass algorithm (similar to the one used to identify the
10055 // best viable function in an overload set) that identifies the
10056 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +000010057
10058 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10059 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10060 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010061
Larisse Voufo43847122013-07-19 23:00:19 +000010062 // TODO: It looks like FailedCandidates does not serve much purpose
10063 // here, since the no_viable diagnostic has index 0.
10064 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith4ad09e62013-09-10 22:59:25 +000010065 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo43847122013-07-19 23:00:19 +000010066 SourceExpr->getLocStart(), S.PDiag(),
10067 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10068 .second->getDeclName(),
10069 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10070 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010071
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010072 if (Result != MatchesCopy.end()) {
10073 // Make it the first and only element
10074 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10075 Matches[0].second = cast<FunctionDecl>(*Result);
10076 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +000010077 }
10078 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010079
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010080 void EliminateAllTemplateMatches() {
10081 // [...] any function template specializations in the set are
10082 // eliminated if the set also contains a non-template function, [...]
10083 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010084 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010085 ++I;
10086 else {
10087 Matches[I] = Matches[--N];
10088 Matches.set_size(N);
10089 }
10090 }
10091 }
10092
10093public:
10094 void ComplainNoMatchesFound() const {
10095 assert(Matches.empty());
10096 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10097 << OvlExpr->getName() << TargetFunctionType
10098 << OvlExpr->getSourceRange();
Richard Smith72a36a12013-08-14 00:00:44 +000010099 if (FailedCandidates.empty())
10100 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10101 else {
10102 // We have some deduction failure messages. Use them to diagnose
10103 // the function templates, and diagnose the non-template candidates
10104 // normally.
10105 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10106 IEnd = OvlExpr->decls_end();
10107 I != IEnd; ++I)
10108 if (FunctionDecl *Fun =
10109 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10110 S.NoteOverloadCandidate(Fun, TargetFunctionType);
10111 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10112 }
10113 }
10114
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010115 bool IsInvalidFormOfPointerToMemberFunction() const {
10116 return TargetTypeIsNonStaticMemberFunction &&
10117 !OvlExprInfo.HasFormOfMemberPointer;
10118 }
David Majnemer576a9af2013-08-01 06:13:59 +000010119
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010120 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10121 // TODO: Should we condition this on whether any functions might
10122 // have matched, or is it more appropriate to do that in callers?
10123 // TODO: a fixit wouldn't hurt.
10124 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10125 << TargetType << OvlExpr->getSourceRange();
10126 }
David Majnemer576a9af2013-08-01 06:13:59 +000010127
10128 bool IsStaticMemberFunctionFromBoundPointer() const {
10129 return StaticMemberFunctionFromBoundPointer;
10130 }
10131
10132 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10133 S.Diag(OvlExpr->getLocStart(),
10134 diag::err_invalid_form_pointer_member_function)
10135 << OvlExpr->getSourceRange();
10136 }
10137
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010138 void ComplainOfInvalidConversion() const {
10139 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10140 << OvlExpr->getName() << TargetType;
10141 }
10142
10143 void ComplainMultipleMatchesFound() const {
10144 assert(Matches.size() > 1);
10145 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10146 << OvlExpr->getName()
10147 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +000010148 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010149 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +000010150
10151 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10152
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010153 int getNumMatches() const { return Matches.size(); }
10154
10155 FunctionDecl* getMatchingFunctionDecl() const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010156 if (Matches.size() != 1) return nullptr;
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010157 return Matches[0].second;
10158 }
10159
10160 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010161 if (Matches.size() != 1) return nullptr;
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010162 return &Matches[0].first;
10163 }
10164};
Stephen Hines176edba2014-12-01 14:53:08 -080010165}
10166
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010167/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10168/// an overloaded function (C++ [over.over]), where @p From is an
10169/// expression with overloaded function type and @p ToType is the type
10170/// we're trying to resolve to. For example:
10171///
10172/// @code
10173/// int f(double);
10174/// int f(int);
10175///
10176/// int (*pfd)(double) = f; // selects f(double)
10177/// @endcode
10178///
10179/// This routine returns the resulting FunctionDecl if it could be
10180/// resolved, and NULL otherwise. When @p Complain is true, this
10181/// routine will emit diagnostics if there is an error.
10182FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +000010183Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10184 QualType TargetType,
10185 bool Complain,
10186 DeclAccessPair &FoundResult,
10187 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010188 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +000010189
10190 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10191 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010192 int NumMatches = Resolver.getNumMatches();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010193 FunctionDecl *Fn = nullptr;
Abramo Bagnara22c107b2011-11-19 11:44:21 +000010194 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010195 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10196 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10197 else
10198 Resolver.ComplainNoMatchesFound();
10199 }
10200 else if (NumMatches > 1 && Complain)
10201 Resolver.ComplainMultipleMatchesFound();
10202 else if (NumMatches == 1) {
10203 Fn = Resolver.getMatchingFunctionDecl();
10204 assert(Fn);
10205 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemer576a9af2013-08-01 06:13:59 +000010206 if (Complain) {
10207 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10208 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10209 else
10210 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10211 }
Sebastian Redl07ab2022009-10-17 21:12:09 +000010212 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +000010213
10214 if (pHadMultipleCandidates)
10215 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010216 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +000010217}
10218
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010219/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +000010220/// resolve that overloaded function expression down to a single function.
10221///
10222/// This routine can only resolve template-ids that refer to a single function
10223/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010224/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +000010225/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker8b407722013-10-20 18:48:56 +000010226///
10227/// If no template-ids are found, no diagnostics are emitted and NULL is
10228/// returned.
John McCall864c0412011-04-26 20:42:42 +000010229FunctionDecl *
10230Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10231 bool Complain,
10232 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +000010233 // C++ [over.over]p1:
10234 // [...] [Note: any redundant set of parentheses surrounding the
10235 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +000010236 // C++ [over.over]p1:
10237 // [...] The overloaded function name can be preceded by the &
10238 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010239
Douglas Gregor4b52e252009-12-21 23:17:24 +000010240 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +000010241 if (!ovl->hasExplicitTemplateArgs())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010242 return nullptr;
John McCall7bb12da2010-02-02 06:20:04 +000010243
10244 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +000010245 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo43847122013-07-19 23:00:19 +000010246 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010247
Douglas Gregor4b52e252009-12-21 23:17:24 +000010248 // Look through all of the overloaded functions, searching for one
10249 // whose type matches exactly.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010250 FunctionDecl *Matched = nullptr;
John McCall864c0412011-04-26 20:42:42 +000010251 for (UnresolvedSetIterator I = ovl->decls_begin(),
10252 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +000010253 // C++0x [temp.arg.explicit]p3:
10254 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010255 // where deduction is not done, if a template argument list is
10256 // specified and it, along with any default template arguments,
10257 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +000010258 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +000010259 FunctionTemplateDecl *FunctionTemplate
10260 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010261
Douglas Gregor4b52e252009-12-21 23:17:24 +000010262 // C++ [over.over]p2:
10263 // If the name is a function template, template argument deduction is
10264 // done (14.8.2.2), and if the argument deduction succeeds, the
10265 // resulting template argument list is used to generate a single
10266 // function template specialization, which is added to the set of
10267 // overloaded functions considered.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010268 FunctionDecl *Specialization = nullptr;
Larisse Voufo43847122013-07-19 23:00:19 +000010269 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor4b52e252009-12-21 23:17:24 +000010270 if (TemplateDeductionResult Result
10271 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor092140a2013-04-17 08:45:07 +000010272 Specialization, Info,
10273 /*InOverloadResolution=*/true)) {
Larisse Voufo43847122013-07-19 23:00:19 +000010274 // Make a note of the failed deduction for diagnostics.
10275 // TODO: Actually use the failed-deduction info?
10276 FailedCandidates.addCandidate()
10277 .set(FunctionTemplate->getTemplatedDecl(),
10278 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor4b52e252009-12-21 23:17:24 +000010279 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010280 }
10281
John McCall864c0412011-04-26 20:42:42 +000010282 assert(Specialization && "no specialization and no error?");
10283
Douglas Gregor4b52e252009-12-21 23:17:24 +000010284 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010285 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010286 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +000010287 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10288 << ovl->getName();
10289 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010290 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010291 return nullptr;
John McCall864c0412011-04-26 20:42:42 +000010292 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +000010293
John McCall864c0412011-04-26 20:42:42 +000010294 Matched = Specialization;
10295 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +000010296 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010297
Stephen Hines176edba2014-12-01 14:53:08 -080010298 if (Matched && getLangOpts().CPlusPlus14 &&
Stephen Hines651f13c2014-04-23 16:59:28 -070010299 Matched->getReturnType()->isUndeducedType() &&
Richard Smith60e141e2013-05-04 07:00:32 +000010300 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010301 return nullptr;
Richard Smith60e141e2013-05-04 07:00:32 +000010302
Douglas Gregor4b52e252009-12-21 23:17:24 +000010303 return Matched;
10304}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010305
Douglas Gregorfadb53b2011-03-12 01:48:56 +000010306
10307
10308
John McCall6dbba4f2011-10-11 23:14:30 +000010309// Resolve and fix an overloaded expression that can be resolved
10310// because it identifies a single function template specialization.
10311//
Douglas Gregorfadb53b2011-03-12 01:48:56 +000010312// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +000010313//
10314// Return true if it was logically possible to so resolve the
10315// expression, regardless of whether or not it succeeded. Always
10316// returns true if 'complain' is set.
10317bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10318 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10319 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +000010320 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +000010321 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +000010322 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +000010323
John McCall6dbba4f2011-10-11 23:14:30 +000010324 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +000010325
John McCall864c0412011-04-26 20:42:42 +000010326 DeclAccessPair found;
10327 ExprResult SingleFunctionExpression;
10328 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10329 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010330 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +000010331 SrcExpr = ExprError();
10332 return true;
10333 }
John McCall864c0412011-04-26 20:42:42 +000010334
10335 // It is only correct to resolve to an instance method if we're
10336 // resolving a form that's permitted to be a pointer to member.
10337 // Otherwise we'll end up making a bound member expression, which
10338 // is illegal in all the contexts we resolve like this.
10339 if (!ovl.HasFormOfMemberPointer &&
10340 isa<CXXMethodDecl>(fn) &&
10341 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +000010342 if (!complain) return false;
10343
10344 Diag(ovl.Expression->getExprLoc(),
10345 diag::err_bound_member_function)
10346 << 0 << ovl.Expression->getSourceRange();
10347
10348 // TODO: I believe we only end up here if there's a mix of
10349 // static and non-static candidates (otherwise the expression
10350 // would have 'bound member' type, not 'overload' type).
10351 // Ideally we would note which candidate was chosen and why
10352 // the static candidates were rejected.
10353 SrcExpr = ExprError();
10354 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +000010355 }
Douglas Gregordb2eae62011-03-16 19:16:25 +000010356
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +000010357 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +000010358 SingleFunctionExpression =
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010359 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall864c0412011-04-26 20:42:42 +000010360
10361 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +000010362 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +000010363 SingleFunctionExpression =
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010364 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall6dbba4f2011-10-11 23:14:30 +000010365 if (SingleFunctionExpression.isInvalid()) {
10366 SrcExpr = ExprError();
10367 return true;
10368 }
10369 }
John McCall864c0412011-04-26 20:42:42 +000010370 }
10371
10372 if (!SingleFunctionExpression.isUsable()) {
10373 if (complain) {
10374 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10375 << ovl.Expression->getName()
10376 << DestTypeForComplaining
10377 << OpRangeForComplaining
10378 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +000010379 NoteAllOverloadCandidates(SrcExpr.get());
10380
10381 SrcExpr = ExprError();
10382 return true;
10383 }
10384
10385 return false;
John McCall864c0412011-04-26 20:42:42 +000010386 }
10387
John McCall6dbba4f2011-10-11 23:14:30 +000010388 SrcExpr = SingleFunctionExpression;
10389 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +000010390}
10391
Douglas Gregor9c6a0e92009-09-22 15:41:20 +000010392/// \brief Add a single candidate to the overload set.
10393static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +000010394 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +000010395 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010396 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +000010397 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +000010398 bool PartialOverloading,
10399 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +000010400 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +000010401 if (isa<UsingShadowDecl>(Callee))
10402 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10403
Douglas Gregor9c6a0e92009-09-22 15:41:20 +000010404 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +000010405 if (ExplicitTemplateArgs) {
10406 assert(!KnownValid && "Explicit template arguments?");
10407 return;
10408 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -070010409 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10410 /*SuppressUsedConversions=*/false,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010411 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +000010412 return;
John McCallba135432009-11-21 08:51:07 +000010413 }
10414
10415 if (FunctionTemplateDecl *FuncTemplate
10416 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +000010417 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Stephen Hines0e2c34f2015-03-23 12:09:02 -070010418 ExplicitTemplateArgs, Args, CandidateSet,
10419 /*SuppressUsedConversions=*/false,
10420 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +000010421 return;
10422 }
10423
Richard Smith2ced0442011-06-26 22:19:54 +000010424 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +000010425}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010426
Douglas Gregor9c6a0e92009-09-22 15:41:20 +000010427/// \brief Add the overload candidates named by callee and/or found by argument
10428/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +000010429void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010430 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +000010431 OverloadCandidateSet &CandidateSet,
10432 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +000010433
10434#ifndef NDEBUG
10435 // Verify that ArgumentDependentLookup is consistent with the rules
10436 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +000010437 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +000010438 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10439 // and let Y be the lookup set produced by argument dependent
10440 // lookup (defined as follows). If X contains
10441 //
10442 // -- a declaration of a class member, or
10443 //
10444 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +000010445 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +000010446 //
10447 // -- a declaration that is neither a function or a function
10448 // template
10449 //
10450 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +000010451
John McCall3b4294e2009-12-16 12:17:52 +000010452 if (ULE->requiresADL()) {
10453 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10454 E = ULE->decls_end(); I != E; ++I) {
10455 assert(!(*I)->getDeclContext()->isRecord());
10456 assert(isa<UsingShadowDecl>(*I) ||
10457 !(*I)->getDeclContext()->isFunctionOrMethod());
10458 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +000010459 }
10460 }
10461#endif
10462
John McCall3b4294e2009-12-16 12:17:52 +000010463 // It would be nice to avoid this copy.
10464 TemplateArgumentListInfo TABuffer;
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010465 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall3b4294e2009-12-16 12:17:52 +000010466 if (ULE->hasExplicitTemplateArgs()) {
10467 ULE->copyTemplateArgumentsInto(TABuffer);
10468 ExplicitTemplateArgs = &TABuffer;
10469 }
10470
10471 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10472 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +000010473 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10474 CandidateSet, PartialOverloading,
10475 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +000010476
John McCall3b4294e2009-12-16 12:17:52 +000010477 if (ULE->requiresADL())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010478 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +000010479 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +000010480 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +000010481}
John McCall578b69b2009-12-16 08:11:27 +000010482
Richard Smithd3ff3252013-06-12 22:56:54 +000010483/// Determine whether a declaration with the specified name could be moved into
10484/// a different namespace.
10485static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10486 switch (Name.getCXXOverloadedOperator()) {
10487 case OO_New: case OO_Array_New:
10488 case OO_Delete: case OO_Array_Delete:
10489 return false;
10490
10491 default:
10492 return true;
10493 }
10494}
10495
Richard Smithf50e88a2011-06-05 22:42:48 +000010496/// Attempt to recover from an ill-formed use of a non-dependent name in a
10497/// template, where the non-dependent name was declared after the template
10498/// was defined. This is common in code written for a compilers which do not
10499/// correctly implement two-stage name lookup.
10500///
10501/// Returns true if a viable candidate was found and a diagnostic was issued.
10502static bool
10503DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10504 const CXXScopeSpec &SS, LookupResult &R,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010505 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smithf50e88a2011-06-05 22:42:48 +000010506 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010507 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010508 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10509 return false;
10510
10511 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +000010512 if (DC->isTransparentContext())
10513 continue;
10514
Richard Smithf50e88a2011-06-05 22:42:48 +000010515 SemaRef.LookupQualifiedName(R, DC);
10516
10517 if (!R.empty()) {
10518 R.suppressDiagnostics();
10519
10520 if (isa<CXXRecordDecl>(DC)) {
10521 // Don't diagnose names we find in classes; we get much better
10522 // diagnostics for these from DiagnoseEmptyLookup.
10523 R.clear();
10524 return false;
10525 }
10526
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010527 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smithf50e88a2011-06-05 22:42:48 +000010528 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10529 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +000010530 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +000010531 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +000010532
10533 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +000010534 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010535 // No viable functions. Don't bother the user with notes for functions
10536 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +000010537 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +000010538 return false;
Richard Smith2ced0442011-06-26 22:19:54 +000010539 }
Richard Smithf50e88a2011-06-05 22:42:48 +000010540
10541 // Find the namespaces where ADL would have looked, and suggest
10542 // declaring the function there instead.
10543 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10544 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +000010545 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +000010546 AssociatedNamespaces,
10547 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +000010548 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithd3ff3252013-06-12 22:56:54 +000010549 if (canBeDeclaredInNamespace(R.getLookupName())) {
10550 DeclContext *Std = SemaRef.getStdNamespace();
10551 for (Sema::AssociatedNamespaceSet::iterator
10552 it = AssociatedNamespaces.begin(),
10553 end = AssociatedNamespaces.end(); it != end; ++it) {
10554 // Never suggest declaring a function within namespace 'std'.
10555 if (Std && Std->Encloses(*it))
10556 continue;
Richard Smith19e0d952012-12-22 02:46:14 +000010557
Richard Smithd3ff3252013-06-12 22:56:54 +000010558 // Never suggest declaring a function within a namespace with a
10559 // reserved name, like __gnu_cxx.
10560 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10561 if (NS &&
10562 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10563 continue;
10564
10565 SuggestedNamespaces.insert(*it);
10566 }
Richard Smithf50e88a2011-06-05 22:42:48 +000010567 }
10568
10569 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10570 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +000010571 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010572 SemaRef.Diag(Best->Function->getLocation(),
10573 diag::note_not_found_by_two_phase_lookup)
10574 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +000010575 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010576 SemaRef.Diag(Best->Function->getLocation(),
10577 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +000010578 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +000010579 } else {
10580 // FIXME: It would be useful to list the associated namespaces here,
10581 // but the diagnostics infrastructure doesn't provide a way to produce
10582 // a localized representation of a list of items.
10583 SemaRef.Diag(Best->Function->getLocation(),
10584 diag::note_not_found_by_two_phase_lookup)
10585 << R.getLookupName() << 2;
10586 }
10587
10588 // Try to recover by calling this function.
10589 return true;
10590 }
10591
10592 R.clear();
10593 }
10594
10595 return false;
10596}
10597
10598/// Attempt to recover from ill-formed use of a non-dependent operator in a
10599/// template, where the non-dependent operator was declared after the template
10600/// was defined.
10601///
10602/// Returns true if a viable candidate was found and a diagnostic was issued.
10603static bool
10604DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10605 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010606 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010607 DeclarationName OpName =
10608 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10609 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10610 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010611 OverloadCandidateSet::CSK_Operator,
10612 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +000010613}
10614
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +000010615namespace {
Richard Smithe49ff3e2012-09-25 04:46:05 +000010616class BuildRecoveryCallExprRAII {
10617 Sema &SemaRef;
10618public:
10619 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10620 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10621 SemaRef.IsBuildingRecoveryCallExpr = true;
10622 }
10623
10624 ~BuildRecoveryCallExprRAII() {
10625 SemaRef.IsBuildingRecoveryCallExpr = false;
10626 }
10627};
10628
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +000010629}
10630
Stephen Hines176edba2014-12-01 14:53:08 -080010631static std::unique_ptr<CorrectionCandidateCallback>
10632MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10633 bool HasTemplateArgs, bool AllowTypoCorrection) {
10634 if (!AllowTypoCorrection)
10635 return llvm::make_unique<NoTypoCorrectionCCC>();
10636 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10637 HasTemplateArgs, ME);
10638}
10639
John McCall578b69b2009-12-16 08:11:27 +000010640/// Attempts to recover from a call where no functions were found.
10641///
10642/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +000010643static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +000010644BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +000010645 UnresolvedLookupExpr *ULE,
10646 SourceLocation LParenLoc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010647 MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +000010648 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010649 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +000010650 // Do not try to recover if it is already building a recovery call.
10651 // This stops infinite loops for template instantiations like
10652 //
10653 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10654 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10655 //
10656 if (SemaRef.IsBuildingRecoveryCallExpr)
10657 return ExprError();
10658 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +000010659
10660 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +000010661 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010662 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +000010663
John McCall3b4294e2009-12-16 12:17:52 +000010664 TemplateArgumentListInfo TABuffer;
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010665 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall3b4294e2009-12-16 12:17:52 +000010666 if (ULE->hasExplicitTemplateArgs()) {
10667 ULE->copyTemplateArgumentsInto(TABuffer);
10668 ExplicitTemplateArgs = &TABuffer;
10669 }
10670
John McCall578b69b2009-12-16 08:11:27 +000010671 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10672 Sema::LookupOrdinaryName);
Richard Smithf50e88a2011-06-05 22:42:48 +000010673 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010674 OverloadCandidateSet::CSK_Normal,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010675 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +000010676 (!EmptyLookup ||
Stephen Hines176edba2014-12-01 14:53:08 -080010677 SemaRef.DiagnoseEmptyLookup(
10678 S, SS, R,
10679 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10680 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10681 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +000010682 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +000010683
John McCall3b4294e2009-12-16 12:17:52 +000010684 assert(!R.empty() && "lookup results empty despite recovery");
10685
10686 // Build an implicit member call if appropriate. Just drop the
10687 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +000010688 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010689 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010690 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10691 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010692 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010693 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010694 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +000010695 else
10696 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10697
10698 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +000010699 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010700
10701 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +000010702 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +000010703 // end up here.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010704 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010705 MultiExprArg(Args.data(), Args.size()),
10706 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +000010707}
Douglas Gregord7a95972010-06-08 17:35:15 +000010708
Sam Panzere1715b62012-08-21 00:52:01 +000010709/// \brief Constructs and populates an OverloadedCandidateSet from
10710/// the given function.
10711/// \returns true when an the ExprResult output parameter has been set.
10712bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10713 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010714 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010715 SourceLocation RParenLoc,
10716 OverloadCandidateSet *CandidateSet,
10717 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +000010718#ifndef NDEBUG
10719 if (ULE->requiresADL()) {
10720 // To do ADL, we must have found an unqualified name.
10721 assert(!ULE->getQualifier() && "qualified name with ADL");
10722
10723 // We don't perform ADL for implicit declarations of builtins.
10724 // Verify that this was correctly set up.
10725 FunctionDecl *F;
10726 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10727 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10728 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +000010729 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010730
John McCall3b4294e2009-12-16 12:17:52 +000010731 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000010732 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +000010733 }
John McCall3b4294e2009-12-16 12:17:52 +000010734#endif
10735
John McCall5acb0c92011-10-17 18:40:02 +000010736 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010737 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzere1715b62012-08-21 00:52:01 +000010738 *Result = ExprError();
10739 return true;
10740 }
Douglas Gregor17330012009-02-04 15:01:18 +000010741
John McCall3b4294e2009-12-16 12:17:52 +000010742 // Add the functions denoted by the callee to the set of candidate
10743 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010744 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +000010745
10746 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +000010747 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10748 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +000010749 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +000010750 // In Microsoft mode, if we are inside a template class member function then
10751 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010752 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +000010753 // classes.
Stephen Hines651f13c2014-04-23 16:59:28 -070010754 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +000010755 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010756 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010757 Context.DependentTy, VK_RValue,
10758 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +000010759 CE->setTypeDependent(true);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010760 *Result = CE;
Sam Panzere1715b62012-08-21 00:52:01 +000010761 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +000010762 }
Sam Panzere1715b62012-08-21 00:52:01 +000010763 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010764 }
John McCall578b69b2009-12-16 08:11:27 +000010765
John McCall5acb0c92011-10-17 18:40:02 +000010766 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +000010767 return false;
10768}
John McCall5acb0c92011-10-17 18:40:02 +000010769
Sam Panzere1715b62012-08-21 00:52:01 +000010770/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10771/// the completed call expression. If overload resolution fails, emits
10772/// diagnostics and returns ExprError()
10773static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10774 UnresolvedLookupExpr *ULE,
10775 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010776 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010777 SourceLocation RParenLoc,
10778 Expr *ExecConfig,
10779 OverloadCandidateSet *CandidateSet,
10780 OverloadCandidateSet::iterator *Best,
10781 OverloadingResult OverloadResult,
10782 bool AllowTypoCorrection) {
10783 if (CandidateSet->empty())
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010784 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010785 RParenLoc, /*EmptyLookup=*/true,
10786 AllowTypoCorrection);
10787
10788 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +000010789 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +000010790 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +000010791 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010792 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10793 return ExprError();
Sam Panzere1715b62012-08-21 00:52:01 +000010794 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010795 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10796 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +000010797 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010798
Richard Smithf50e88a2011-06-05 22:42:48 +000010799 case OR_No_Viable_Function: {
10800 // Try to recover by looking for viable functions which the user might
10801 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +000010802 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010803 Args, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010804 /*EmptyLookup=*/false,
10805 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +000010806 if (!Recovery.isInvalid())
10807 return Recovery;
10808
Sam Panzere1715b62012-08-21 00:52:01 +000010809 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +000010810 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +000010811 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010812 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010813 break;
Richard Smithf50e88a2011-06-05 22:42:48 +000010814 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010815
10816 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +000010817 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +000010818 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010819 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010820 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010821
Sam Panzere1715b62012-08-21 00:52:01 +000010822 case OR_Deleted: {
10823 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10824 << (*Best)->Function->isDeleted()
10825 << ULE->getName()
10826 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10827 << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010828 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +000010829
Sam Panzere1715b62012-08-21 00:52:01 +000010830 // We emitted an error for the unvailable/deleted function call but keep
10831 // the call in the AST.
10832 FunctionDecl *FDecl = (*Best)->Function;
10833 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010834 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10835 ExecConfig);
Sam Panzere1715b62012-08-21 00:52:01 +000010836 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010837 }
10838
Douglas Gregorff331c12010-07-25 18:17:45 +000010839 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +000010840 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +000010841}
10842
Sam Panzere1715b62012-08-21 00:52:01 +000010843/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10844/// (which eventually refers to the declaration Func) and the call
10845/// arguments Args/NumArgs, attempt to resolve the function call down
10846/// to a specific function. If overload resolution succeeds, returns
10847/// the call expression produced by overload resolution.
10848/// Otherwise, emits diagnostics and returns ExprError.
10849ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10850 UnresolvedLookupExpr *ULE,
10851 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010852 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010853 SourceLocation RParenLoc,
10854 Expr *ExecConfig,
10855 bool AllowTypoCorrection) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010856 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10857 OverloadCandidateSet::CSK_Normal);
Sam Panzere1715b62012-08-21 00:52:01 +000010858 ExprResult result;
10859
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010860 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10861 &result))
Sam Panzere1715b62012-08-21 00:52:01 +000010862 return result;
10863
10864 OverloadCandidateSet::iterator Best;
10865 OverloadingResult OverloadResult =
10866 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10867
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010868 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010869 RParenLoc, ExecConfig, &CandidateSet,
10870 &Best, OverloadResult,
10871 AllowTypoCorrection);
10872}
10873
John McCall6e266892010-01-26 03:27:55 +000010874static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010875 return Functions.size() > 1 ||
10876 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10877}
10878
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010879/// \brief Create a unary operation that may resolve to an overloaded
10880/// operator.
10881///
10882/// \param OpLoc The location of the operator itself (e.g., '*').
10883///
10884/// \param OpcIn The UnaryOperator::Opcode that describes this
10885/// operator.
10886///
James Dennett40ae6662012-06-22 08:52:37 +000010887/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010888/// considered by overload resolution. The caller needs to build this
10889/// set based on the context using, e.g.,
10890/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10891/// set should not contain any member functions; those will be added
10892/// by CreateOverloadedUnaryOp().
10893///
James Dennett8da16872012-06-22 10:32:46 +000010894/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010895ExprResult
John McCall6e266892010-01-26 03:27:55 +000010896Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10897 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010898 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010899 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010900
10901 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10902 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10903 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010904 // TODO: provide better source location info.
10905 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010906
John McCall5acb0c92011-10-17 18:40:02 +000010907 if (checkPlaceholderForOverload(*this, Input))
10908 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010909
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010910 Expr *Args[2] = { Input, nullptr };
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010911 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010912
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010913 // For post-increment and post-decrement, add the implicit '0' as
10914 // the second argument, so that we know this is a post-increment or
10915 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010916 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010917 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010918 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10919 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010920 NumArgs = 2;
10921 }
10922
Richard Smith958ba642013-05-05 15:51:06 +000010923 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10924
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010925 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010926 if (Fns.empty())
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010927 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10928 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010929
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010930 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010931 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010932 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010933 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010934 /*ADL*/ true, IsOverloaded(Fns),
10935 Fns.begin(), Fns.end());
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010936 return new (Context)
10937 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10938 VK_RValue, OpLoc, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010939 }
10940
10941 // Build an empty overload set.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010942 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010943
10944 // Add the candidates from the given function set.
Stephen Hines0e2c34f2015-03-23 12:09:02 -070010945 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010946
10947 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010948 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010949
John McCall6e266892010-01-26 03:27:55 +000010950 // Add candidates from ADL.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010951 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
10952 /*ExplicitTemplateArgs*/nullptr,
John McCall6e266892010-01-26 03:27:55 +000010953 CandidateSet);
10954
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010955 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010956 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010957
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010958 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10959
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010960 // Perform overload resolution.
10961 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010962 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010963 case OR_Success: {
10964 // We found a built-in operator or an overloaded operator.
10965 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010966
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010967 if (FnDecl) {
10968 // We matched an overloaded operator. Build a call to that
10969 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010970
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010971 // Convert the arguments.
10972 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010973 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010974
John Wiegley429bb272011-04-08 18:41:53 +000010975 ExprResult InputRes =
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010976 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley429bb272011-04-08 18:41:53 +000010977 Best->FoundDecl, Method);
10978 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010979 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010980 Input = InputRes.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010981 } else {
10982 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010983 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010984 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010985 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010986 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010987 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010988 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010989 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010990 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010991 Input = InputInit.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010992 }
10993
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010994 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010995 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010996 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010997 if (FnExpr.isInvalid())
10998 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010999
Richard Smithf93ec762013-11-15 02:58:23 +000011000 // Determine the result type.
Stephen Hines651f13c2014-04-23 16:59:28 -070011001 QualType ResultTy = FnDecl->getReturnType();
Richard Smithf93ec762013-11-15 02:58:23 +000011002 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11003 ResultTy = ResultTy.getNonLValueExprType(Context);
11004
Eli Friedman4c3b8962009-11-18 03:58:17 +000011005 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000011006 CallExpr *TheCall =
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011007 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hamesbe9af122012-10-02 04:45:10 +000011008 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000011009
Stephen Hines651f13c2014-04-23 16:59:28 -070011010 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlsson26a2a072009-10-13 21:19:37 +000011011 return ExprError();
11012
John McCall9ae2f072010-08-23 23:25:46 +000011013 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000011014 } else {
11015 // We matched a built-in operator. Convert the arguments, then
11016 // break out so that we will build the appropriate built-in
11017 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000011018 ExprResult InputRes =
11019 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11020 Best->Conversions[0], AA_Passing);
11021 if (InputRes.isInvalid())
11022 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011023 Input = InputRes.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000011024 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000011025 }
John Wiegley429bb272011-04-08 18:41:53 +000011026 }
11027
11028 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000011029 // This is an erroneous use of an operator which can be overloaded by
11030 // a non-member function. Check for non-member operators which were
11031 // defined too late to be candidates.
Richard Smith958ba642013-05-05 15:51:06 +000011032 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smithf50e88a2011-06-05 22:42:48 +000011033 // FIXME: Recover by calling the found function.
11034 return ExprError();
11035
John Wiegley429bb272011-04-08 18:41:53 +000011036 // No viable function; fall through to handling this as a
11037 // built-in operator, which will produce an error message for us.
11038 break;
11039
11040 case OR_Ambiguous:
11041 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11042 << UnaryOperator::getOpcodeStr(Opc)
11043 << Input->getType()
11044 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000011045 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley429bb272011-04-08 18:41:53 +000011046 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11047 return ExprError();
11048
11049 case OR_Deleted:
11050 Diag(OpLoc, diag::err_ovl_deleted_oper)
11051 << Best->Function->isDeleted()
11052 << UnaryOperator::getOpcodeStr(Opc)
11053 << getDeletedOrUnavailableSuffix(Best->Function)
11054 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000011055 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman1795d372011-08-26 19:46:22 +000011056 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011057 return ExprError();
11058 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000011059
11060 // Either we found no viable overloaded operator or we matched a
11061 // built-in operator. In either case, fall through to trying to
11062 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000011063 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000011064}
11065
Douglas Gregor063daf62009-03-13 18:40:31 +000011066/// \brief Create a binary operation that may resolve to an overloaded
11067/// operator.
11068///
11069/// \param OpLoc The location of the operator itself (e.g., '+').
11070///
11071/// \param OpcIn The BinaryOperator::Opcode that describes this
11072/// operator.
11073///
James Dennett40ae6662012-06-22 08:52:37 +000011074/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000011075/// considered by overload resolution. The caller needs to build this
11076/// set based on the context using, e.g.,
11077/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11078/// set should not contain any member functions; those will be added
11079/// by CreateOverloadedBinOp().
11080///
11081/// \param LHS Left-hand argument.
11082/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000011083ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000011084Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000011085 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000011086 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000011087 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000011088 Expr *Args[2] = { LHS, RHS };
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011089 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000011090
11091 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11092 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11093 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11094
11095 // If either side is type-dependent, create an appropriate dependent
11096 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000011097 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000011098 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011099 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000011100 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000011101 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011102 return new (Context) BinaryOperator(
11103 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11104 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011105
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011106 return new (Context) CompoundAssignOperator(
11107 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11108 Context.DependentTy, Context.DependentTy, OpLoc,
11109 FPFeatures.fp_contract);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000011110 }
John McCall6e266892010-01-26 03:27:55 +000011111
11112 // FIXME: save results of ADL from here?
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011113 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000011114 // TODO: provide better source location info in DNLoc component.
11115 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000011116 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000011117 = UnresolvedLookupExpr::Create(Context, NamingClass,
11118 NestedNameSpecifierLoc(), OpNameInfo,
11119 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000011120 Fns.begin(), Fns.end());
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011121 return new (Context)
11122 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11123 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor063daf62009-03-13 18:40:31 +000011124 }
11125
John McCall5acb0c92011-10-17 18:40:02 +000011126 // Always do placeholder-like conversions on the RHS.
11127 if (checkPlaceholderForOverload(*this, Args[1]))
11128 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011129
John McCall3c3b7f92011-10-25 17:37:35 +000011130 // Do placeholder-like conversion on the LHS; note that we should
11131 // not get here with a PseudoObject LHS.
11132 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000011133 if (checkPlaceholderForOverload(*this, Args[0]))
11134 return ExprError();
11135
Sebastian Redl275c2b42009-11-18 23:10:33 +000011136 // If this is the assignment operator, we only perform overload resolution
11137 // if the left-hand side is a class or enumeration type. This is actually
11138 // a hack. The standard requires that we do overload resolution between the
11139 // various built-in candidates, but as DR507 points out, this can lead to
11140 // problems. So we do it this way, which pretty much follows what GCC does.
11141 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000011142 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000011143 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000011144
John McCall0e800c92010-12-04 08:14:53 +000011145 // If this is the .* operator, which is not overloadable, just
11146 // create a built-in binary operator.
11147 if (Opc == BO_PtrMemD)
11148 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11149
Douglas Gregorbc736fc2009-03-13 23:49:33 +000011150 // Build an empty overload set.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011151 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor063daf62009-03-13 18:40:31 +000011152
11153 // Add the candidates from the given function set.
Stephen Hines0e2c34f2015-03-23 12:09:02 -070011154 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000011155
11156 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000011157 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000011158
Stephen Hines176edba2014-12-01 14:53:08 -080011159 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11160 // performed for an assignment operator (nor for operator[] nor operator->,
11161 // which don't get here).
11162 if (Opc != BO_Assign)
11163 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11164 /*ExplicitTemplateArgs*/ nullptr,
11165 CandidateSet);
John McCall6e266892010-01-26 03:27:55 +000011166
Douglas Gregor063daf62009-03-13 18:40:31 +000011167 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000011168 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000011169
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011170 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11171
Douglas Gregor063daf62009-03-13 18:40:31 +000011172 // Perform overload resolution.
11173 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011174 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000011175 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000011176 // We found a built-in operator or an overloaded operator.
11177 FunctionDecl *FnDecl = Best->Function;
11178
11179 if (FnDecl) {
11180 // We matched an overloaded operator. Build a call to that
11181 // operator.
11182
11183 // Convert the arguments.
11184 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000011185 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000011186 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000011187
Chandler Carruth6df868e2010-12-12 08:17:55 +000011188 ExprResult Arg1 =
11189 PerformCopyInitialization(
11190 InitializedEntity::InitializeParameter(Context,
11191 FnDecl->getParamDecl(0)),
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011192 SourceLocation(), Args[1]);
Douglas Gregor4c2458a2009-12-22 21:44:34 +000011193 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000011194 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000011195
John Wiegley429bb272011-04-08 18:41:53 +000011196 ExprResult Arg0 =
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011197 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley429bb272011-04-08 18:41:53 +000011198 Best->FoundDecl, Method);
11199 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000011200 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011201 Args[0] = Arg0.getAs<Expr>();
11202 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000011203 } else {
11204 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000011205 ExprResult Arg0 = PerformCopyInitialization(
11206 InitializedEntity::InitializeParameter(Context,
11207 FnDecl->getParamDecl(0)),
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011208 SourceLocation(), Args[0]);
Douglas Gregor4c2458a2009-12-22 21:44:34 +000011209 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000011210 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000011211
Chandler Carruth6df868e2010-12-12 08:17:55 +000011212 ExprResult Arg1 =
11213 PerformCopyInitialization(
11214 InitializedEntity::InitializeParameter(Context,
11215 FnDecl->getParamDecl(1)),
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011216 SourceLocation(), Args[1]);
Douglas Gregor4c2458a2009-12-22 21:44:34 +000011217 if (Arg1.isInvalid())
11218 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011219 Args[0] = LHS = Arg0.getAs<Expr>();
11220 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000011221 }
11222
Douglas Gregor063daf62009-03-13 18:40:31 +000011223 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011224 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011225 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011226 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011227 if (FnExpr.isInvalid())
11228 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000011229
Richard Smithf93ec762013-11-15 02:58:23 +000011230 // Determine the result type.
Stephen Hines651f13c2014-04-23 16:59:28 -070011231 QualType ResultTy = FnDecl->getReturnType();
Richard Smithf93ec762013-11-15 02:58:23 +000011232 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11233 ResultTy = ResultTy.getNonLValueExprType(Context);
11234
John McCall9ae2f072010-08-23 23:25:46 +000011235 CXXOperatorCallExpr *TheCall =
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011236 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011237 Args, ResultTy, VK, OpLoc,
11238 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011239
Stephen Hines651f13c2014-04-23 16:59:28 -070011240 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011241 FnDecl))
11242 return ExprError();
11243
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000011244 ArrayRef<const Expr *> ArgsArray(Args, 2);
11245 // Cut off the implicit 'this'.
11246 if (isa<CXXMethodDecl>(FnDecl))
11247 ArgsArray = ArgsArray.slice(1);
Stephen Hines0e2c34f2015-03-23 12:09:02 -070011248
11249 // Check for a self move.
11250 if (Op == OO_Equal)
11251 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11252
11253 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000011254 TheCall->getSourceRange(), VariadicDoesNotApply);
11255
John McCall9ae2f072010-08-23 23:25:46 +000011256 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000011257 } else {
11258 // We matched a built-in operator. Convert the arguments, then
11259 // break out so that we will build the appropriate built-in
11260 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000011261 ExprResult ArgsRes0 =
11262 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11263 Best->Conversions[0], AA_Passing);
11264 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000011265 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011266 Args[0] = ArgsRes0.get();
Douglas Gregor063daf62009-03-13 18:40:31 +000011267
John Wiegley429bb272011-04-08 18:41:53 +000011268 ExprResult ArgsRes1 =
11269 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11270 Best->Conversions[1], AA_Passing);
11271 if (ArgsRes1.isInvalid())
11272 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011273 Args[1] = ArgsRes1.get();
Douglas Gregor063daf62009-03-13 18:40:31 +000011274 break;
11275 }
11276 }
11277
Douglas Gregor33074752009-09-30 21:46:01 +000011278 case OR_No_Viable_Function: {
11279 // C++ [over.match.oper]p9:
11280 // If the operator is the operator , [...] and there are no
11281 // viable functions, then the operator is assumed to be the
11282 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000011283 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000011284 break;
11285
Chandler Carruth6df868e2010-12-12 08:17:55 +000011286 // For class as left operand for assignment or compound assigment
11287 // operator do not fall through to handling in built-in, but report that
11288 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000011289 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011290 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000011291 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000011292 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11293 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000011294 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman3f93d4c2013-08-28 20:35:35 +000011295 if (Args[0]->getType()->isIncompleteType()) {
11296 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11297 << Args[0]->getType()
11298 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11299 }
Douglas Gregor33074752009-09-30 21:46:01 +000011300 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000011301 // This is an erroneous use of an operator which can be overloaded by
11302 // a non-member function. Check for non-member operators which were
11303 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000011304 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000011305 // FIXME: Recover by calling the found function.
11306 return ExprError();
11307
Douglas Gregor33074752009-09-30 21:46:01 +000011308 // No viable function; try to create a built-in operation, which will
11309 // produce an error. Then, show the non-viable candidates.
11310 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000011311 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011312 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000011313 "C++ binary operator overloading is missing candidates!");
11314 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000011315 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000011316 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011317 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000011318 }
Douglas Gregor063daf62009-03-13 18:40:31 +000011319
11320 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011321 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000011322 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000011323 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000011324 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011325 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000011326 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000011327 return ExprError();
11328
11329 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000011330 if (isImplicitlyDeleted(Best->Function)) {
11331 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11332 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000011333 << Context.getRecordType(Method->getParent())
11334 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000011335
Richard Smith0f46e642012-12-28 12:23:24 +000011336 // The user probably meant to call this special member. Just
11337 // explain why it's deleted.
11338 NoteDeletedFunction(Method);
11339 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000011340 } else {
11341 Diag(OpLoc, diag::err_ovl_deleted_oper)
11342 << Best->Function->isDeleted()
11343 << BinaryOperator::getOpcodeStr(Opc)
11344 << getDeletedOrUnavailableSuffix(Best->Function)
11345 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11346 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000011347 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000011348 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000011349 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000011350 }
Douglas Gregor063daf62009-03-13 18:40:31 +000011351
Douglas Gregor33074752009-09-30 21:46:01 +000011352 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000011353 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000011354}
11355
John McCall60d7b3a2010-08-24 06:29:42 +000011356ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000011357Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11358 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000011359 Expr *Base, Expr *Idx) {
11360 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000011361 DeclarationName OpName =
11362 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11363
11364 // If either side is type-dependent, create an appropriate dependent
11365 // expression.
11366 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11367
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011368 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000011369 // CHECKME: no 'operator' keyword?
11370 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11371 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000011372 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000011373 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000011374 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000011375 /*ADL*/ true, /*Overloaded*/ false,
11376 UnresolvedSetIterator(),
11377 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000011378 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000011379
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011380 return new (Context)
11381 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11382 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000011383 }
11384
John McCall5acb0c92011-10-17 18:40:02 +000011385 // Handle placeholders on both operands.
11386 if (checkPlaceholderForOverload(*this, Args[0]))
11387 return ExprError();
11388 if (checkPlaceholderForOverload(*this, Args[1]))
11389 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011390
Sebastian Redlf322ed62009-10-29 20:17:01 +000011391 // Build an empty overload set.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011392 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redlf322ed62009-10-29 20:17:01 +000011393
11394 // Subscript can only be overloaded as a member function.
11395
11396 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000011397 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000011398
11399 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000011400 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000011401
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011402 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11403
Sebastian Redlf322ed62009-10-29 20:17:01 +000011404 // Perform overload resolution.
11405 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011406 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000011407 case OR_Success: {
11408 // We found a built-in operator or an overloaded operator.
11409 FunctionDecl *FnDecl = Best->Function;
11410
11411 if (FnDecl) {
11412 // We matched an overloaded operator. Build a call to that
11413 // operator.
11414
John McCall9aa472c2010-03-19 07:35:19 +000011415 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000011416
Sebastian Redlf322ed62009-10-29 20:17:01 +000011417 // Convert the arguments.
11418 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000011419 ExprResult Arg0 =
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011420 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley429bb272011-04-08 18:41:53 +000011421 Best->FoundDecl, Method);
11422 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000011423 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011424 Args[0] = Arg0.get();
Sebastian Redlf322ed62009-10-29 20:17:01 +000011425
Anders Carlsson38f88ab2010-01-29 18:37:50 +000011426 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000011427 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000011428 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011429 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000011430 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011431 SourceLocation(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011432 Args[1]);
Anders Carlsson38f88ab2010-01-29 18:37:50 +000011433 if (InputInit.isInvalid())
11434 return ExprError();
11435
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011436 Args[1] = InputInit.getAs<Expr>();
Anders Carlsson38f88ab2010-01-29 18:37:50 +000011437
Sebastian Redlf322ed62009-10-29 20:17:01 +000011438 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011439 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11440 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011441 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011442 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011443 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011444 OpLocInfo.getLoc(),
11445 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011446 if (FnExpr.isInvalid())
11447 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000011448
Richard Smithf93ec762013-11-15 02:58:23 +000011449 // Determine the result type
Stephen Hines651f13c2014-04-23 16:59:28 -070011450 QualType ResultTy = FnDecl->getReturnType();
Richard Smithf93ec762013-11-15 02:58:23 +000011451 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11452 ResultTy = ResultTy.getNonLValueExprType(Context);
11453
John McCall9ae2f072010-08-23 23:25:46 +000011454 CXXOperatorCallExpr *TheCall =
11455 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011456 FnExpr.get(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000011457 ResultTy, VK, RLoc,
11458 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000011459
Stephen Hines651f13c2014-04-23 16:59:28 -070011460 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redlf322ed62009-10-29 20:17:01 +000011461 return ExprError();
11462
John McCall9ae2f072010-08-23 23:25:46 +000011463 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000011464 } else {
11465 // We matched a built-in operator. Convert the arguments, then
11466 // break out so that we will build the appropriate built-in
11467 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000011468 ExprResult ArgsRes0 =
11469 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11470 Best->Conversions[0], AA_Passing);
11471 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000011472 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011473 Args[0] = ArgsRes0.get();
John Wiegley429bb272011-04-08 18:41:53 +000011474
11475 ExprResult ArgsRes1 =
11476 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11477 Best->Conversions[1], AA_Passing);
11478 if (ArgsRes1.isInvalid())
11479 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011480 Args[1] = ArgsRes1.get();
Sebastian Redlf322ed62009-10-29 20:17:01 +000011481
11482 break;
11483 }
11484 }
11485
11486 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000011487 if (CandidateSet.empty())
11488 Diag(LLoc, diag::err_ovl_no_oper)
11489 << Args[0]->getType() << /*subscript*/ 0
11490 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11491 else
11492 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11493 << Args[0]->getType()
11494 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011495 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000011496 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000011497 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000011498 }
11499
11500 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011501 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011502 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000011503 << Args[0]->getType() << Args[1]->getType()
11504 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011505 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000011506 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000011507 return ExprError();
11508
11509 case OR_Deleted:
11510 Diag(LLoc, diag::err_ovl_deleted_oper)
11511 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011512 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000011513 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011514 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000011515 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000011516 return ExprError();
11517 }
11518
11519 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000011520 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000011521}
11522
Douglas Gregor88a35142008-12-22 05:46:06 +000011523/// BuildCallToMemberFunction - Build a call to a member
11524/// function. MemExpr is the expression that refers to the member
11525/// function (and includes the object parameter), Args/NumArgs are the
11526/// arguments to the function call (not including the object
11527/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000011528/// expression refers to a non-static member function or an overloaded
11529/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000011530ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000011531Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011532 SourceLocation LParenLoc,
11533 MultiExprArg Args,
11534 SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000011535 assert(MemExprE->getType() == Context.BoundMemberTy ||
11536 MemExprE->getType() == Context.OverloadTy);
11537
Douglas Gregor88a35142008-12-22 05:46:06 +000011538 // Dig out the member expression. This holds both the object
11539 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000011540 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011541
John McCall864c0412011-04-26 20:42:42 +000011542 // Determine whether this is a call to a pointer-to-member function.
11543 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11544 assert(op->getType() == Context.BoundMemberTy);
11545 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11546
11547 QualType fnType =
11548 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11549
11550 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11551 QualType resultType = proto->getCallResultType(Context);
Stephen Hines651f13c2014-04-23 16:59:28 -070011552 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall864c0412011-04-26 20:42:42 +000011553
11554 // Check that the object type isn't more qualified than the
11555 // member function we're calling.
11556 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11557
11558 QualType objectType = op->getLHS()->getType();
11559 if (op->getOpcode() == BO_PtrMemI)
11560 objectType = objectType->castAs<PointerType>()->getPointeeType();
11561 Qualifiers objectQuals = objectType.getQualifiers();
11562
11563 Qualifiers difference = objectQuals - funcQuals;
11564 difference.removeObjCGCAttr();
11565 difference.removeAddressSpace();
11566 if (difference) {
11567 std::string qualsString = difference.getAsString();
11568 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11569 << fnType.getUnqualifiedType()
11570 << qualsString
11571 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11572 }
Stephen Hines651f13c2014-04-23 16:59:28 -070011573
Stephen Hines176edba2014-12-01 14:53:08 -080011574 if (resultType->isMemberPointerType())
11575 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11576 RequireCompleteType(LParenLoc, resultType, 0);
11577
John McCall864c0412011-04-26 20:42:42 +000011578 CXXMemberCallExpr *call
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011579 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall864c0412011-04-26 20:42:42 +000011580 resultType, valueKind, RParenLoc);
11581
Stephen Hines651f13c2014-04-23 16:59:28 -070011582 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011583 call, nullptr))
John McCall864c0412011-04-26 20:42:42 +000011584 return ExprError();
11585
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011586 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall864c0412011-04-26 20:42:42 +000011587 return ExprError();
11588
Richard Trieue2a90b82013-06-22 02:30:38 +000011589 if (CheckOtherCall(call, proto))
11590 return ExprError();
11591
John McCall864c0412011-04-26 20:42:42 +000011592 return MaybeBindToTemporary(call);
11593 }
11594
Stephen Hines0e2c34f2015-03-23 12:09:02 -070011595 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11596 return new (Context)
11597 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11598
John McCall5acb0c92011-10-17 18:40:02 +000011599 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011600 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011601 return ExprError();
11602
John McCall129e2df2009-11-30 22:42:35 +000011603 MemberExpr *MemExpr;
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011604 CXXMethodDecl *Method = nullptr;
11605 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11606 NestedNameSpecifier *Qualifier = nullptr;
John McCall129e2df2009-11-30 22:42:35 +000011607 if (isa<MemberExpr>(NakedMemExpr)) {
11608 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000011609 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000011610 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000011611 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000011612 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000011613 } else {
11614 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000011615 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011616
John McCall701c89e2009-12-03 04:06:58 +000011617 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011618 Expr::Classification ObjectClassification
11619 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11620 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000011621
Douglas Gregor88a35142008-12-22 05:46:06 +000011622 // Add overload candidates
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011623 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11624 OverloadCandidateSet::CSK_Normal);
Mike Stump1eb44332009-09-09 15:08:12 +000011625
John McCallaa81e162009-12-01 22:10:20 +000011626 // FIXME: avoid copy.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011627 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCallaa81e162009-12-01 22:10:20 +000011628 if (UnresExpr->hasExplicitTemplateArgs()) {
11629 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11630 TemplateArgs = &TemplateArgsBuffer;
11631 }
11632
John McCall129e2df2009-11-30 22:42:35 +000011633 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11634 E = UnresExpr->decls_end(); I != E; ++I) {
11635
John McCall701c89e2009-12-03 04:06:58 +000011636 NamedDecl *Func = *I;
11637 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11638 if (isa<UsingShadowDecl>(Func))
11639 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11640
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011641
Francois Pichetdbee3412011-01-18 05:04:39 +000011642 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000011643 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000011644 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011645 Args, CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000011646 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000011647 // If explicit template arguments were provided, we can't call a
11648 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000011649 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000011650 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011651
John McCall9aa472c2010-03-19 07:35:19 +000011652 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011653 ObjectClassification, Args, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011654 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000011655 } else {
John McCall129e2df2009-11-30 22:42:35 +000011656 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000011657 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011658 ObjectType, ObjectClassification,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011659 Args, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000011660 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000011661 }
Douglas Gregordec06662009-08-21 18:42:58 +000011662 }
Mike Stump1eb44332009-09-09 15:08:12 +000011663
John McCall129e2df2009-11-30 22:42:35 +000011664 DeclarationName DeclName = UnresExpr->getMemberName();
11665
John McCall5acb0c92011-10-17 18:40:02 +000011666 UnbridgedCasts.restore();
11667
Douglas Gregor88a35142008-12-22 05:46:06 +000011668 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011669 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000011670 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000011671 case OR_Success:
11672 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000011673 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000011674 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011675 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11676 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011677 // If FoundDecl is different from Method (such as if one is a template
11678 // and the other a specialization), make sure DiagnoseUseOfDecl is
11679 // called on both.
11680 // FIXME: This would be more comprehensively addressed by modifying
11681 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11682 // being used.
11683 if (Method != FoundDecl.getDecl() &&
11684 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11685 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011686 break;
11687
11688 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000011689 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000011690 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011691 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011692 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011693 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011694 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011695
11696 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000011697 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011698 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011699 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011700 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011701 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011702
11703 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000011704 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011705 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011706 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011707 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011708 << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011709 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011710 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011711 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011712 }
11713
John McCall6bb80172010-03-30 21:47:33 +000011714 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000011715
John McCallaa81e162009-12-01 22:10:20 +000011716 // If overload resolution picked a static member, build a
11717 // non-member call based on that function.
11718 if (Method->isStatic()) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011719 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11720 RParenLoc);
John McCallaa81e162009-12-01 22:10:20 +000011721 }
11722
John McCall129e2df2009-11-30 22:42:35 +000011723 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000011724 }
11725
Stephen Hines651f13c2014-04-23 16:59:28 -070011726 QualType ResultType = Method->getReturnType();
John McCallf89e55a2010-11-18 06:31:45 +000011727 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11728 ResultType = ResultType.getNonLValueExprType(Context);
11729
Douglas Gregor88a35142008-12-22 05:46:06 +000011730 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011731 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011732 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCallf89e55a2010-11-18 06:31:45 +000011733 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000011734
Stephen Hines176edba2014-12-01 14:53:08 -080011735 // (CUDA B.1): Check for invalid calls between targets.
11736 if (getLangOpts().CUDA) {
11737 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11738 if (CheckCUDATarget(Caller, Method)) {
11739 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11740 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11741 << IdentifyCUDATarget(Caller);
11742 return ExprError();
11743 }
11744 }
11745 }
11746
Anders Carlssoneed3e692009-10-10 00:06:20 +000011747 // Check for a valid return type.
Stephen Hines651f13c2014-04-23 16:59:28 -070011748 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000011749 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000011750 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011751
Douglas Gregor88a35142008-12-22 05:46:06 +000011752 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000011753 // We only need to do this if there was actually an overload; otherwise
11754 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000011755 if (!Method->isStatic()) {
11756 ExprResult ObjectArg =
11757 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11758 FoundDecl, Method);
11759 if (ObjectArg.isInvalid())
11760 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011761 MemExpr->setBase(ObjectArg.get());
John Wiegley429bb272011-04-08 18:41:53 +000011762 }
Douglas Gregor88a35142008-12-22 05:46:06 +000011763
11764 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000011765 const FunctionProtoType *Proto =
11766 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011767 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor88a35142008-12-22 05:46:06 +000011768 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000011769 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011770
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011771 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011772
Richard Smith831421f2012-06-25 20:30:08 +000011773 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000011774 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000011775
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011776 if ((isa<CXXConstructorDecl>(CurContext) ||
11777 isa<CXXDestructorDecl>(CurContext)) &&
11778 TheCall->getMethodDecl()->isPure()) {
11779 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11780
Chandler Carruthae198062011-06-27 08:31:58 +000011781 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011782 Diag(MemExpr->getLocStart(),
11783 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11784 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11785 << MD->getParent()->getDeclName();
11786
11787 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000011788 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011789 }
John McCall9ae2f072010-08-23 23:25:46 +000011790 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000011791}
11792
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011793/// BuildCallToObjectOfClassType - Build a call to an object of class
11794/// type (C++ [over.call.object]), which can end up invoking an
11795/// overloaded function call operator (@c operator()) or performing a
11796/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000011797ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000011798Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000011799 SourceLocation LParenLoc,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011800 MultiExprArg Args,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011801 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000011802 if (checkPlaceholderForOverload(*this, Obj))
11803 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011804 ExprResult Object = Obj;
John McCall5acb0c92011-10-17 18:40:02 +000011805
11806 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011807 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011808 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011809
Stephen Hines176edba2014-12-01 14:53:08 -080011810 assert(Object.get()->getType()->isRecordType() &&
11811 "Requires object type argument");
John Wiegley429bb272011-04-08 18:41:53 +000011812 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000011813
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011814 // C++ [over.call.object]p1:
11815 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000011816 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011817 // candidate functions includes at least the function call
11818 // operators of T. The function call operators of T are obtained by
11819 // ordinary lookup of the name operator() in the context of
11820 // (E).operator().
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011821 OverloadCandidateSet CandidateSet(LParenLoc,
11822 OverloadCandidateSet::CSK_Operator);
Douglas Gregor44b43212008-12-11 16:49:14 +000011823 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000011824
John Wiegley429bb272011-04-08 18:41:53 +000011825 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011826 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000011827 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011828
John McCalla24dc2e2009-11-17 02:14:36 +000011829 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11830 LookupQualifiedName(R, Record->getDecl());
11831 R.suppressDiagnostics();
11832
Douglas Gregor593564b2009-11-15 07:48:03 +000011833 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000011834 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000011835 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011836 Object.get()->Classify(Context),
11837 Args, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000011838 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000011839 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011840
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011841 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011842 // In addition, for each (non-explicit in C++0x) conversion function
11843 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011844 //
11845 // operator conversion-type-id () cv-qualifier;
11846 //
11847 // where cv-qualifier is the same cv-qualification as, or a
11848 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000011849 // denotes the type "pointer to function of (P1,...,Pn) returning
11850 // R", or the type "reference to pointer to function of
11851 // (P1,...,Pn) returning R", or the type "reference to function
11852 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011853 // is also considered as a candidate function. Similarly,
11854 // surrogate call functions are added to the set of candidate
11855 // functions for each conversion function declared in an
11856 // accessible base class provided the function is not hidden
11857 // within T by another intervening declaration.
Stephen Hines0e2c34f2015-03-23 12:09:02 -070011858 const auto &Conversions =
11859 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11860 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000011861 NamedDecl *D = *I;
11862 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11863 if (isa<UsingShadowDecl>(D))
11864 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011865
Douglas Gregor4a27d702009-10-21 06:18:39 +000011866 // Skip over templated conversion functions; they aren't
11867 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000011868 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000011869 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000011870
John McCall701c89e2009-12-03 04:06:58 +000011871 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011872 if (!Conv->isExplicit()) {
11873 // Strip the reference type (if any) and then the pointer type (if
11874 // any) to get down to what might be a function type.
11875 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11876 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11877 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011878
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011879 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11880 {
11881 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011882 Object.get(), Args, CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011883 }
11884 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011885 }
Mike Stump1eb44332009-09-09 15:08:12 +000011886
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011887 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11888
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011889 // Perform overload resolution.
11890 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011891 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011892 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011893 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011894 // Overload resolution succeeded; we'll build the appropriate call
11895 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011896 break;
11897
11898 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011899 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011900 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011901 << Object.get()->getType() << /*call*/ 1
11902 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011903 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011904 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011905 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011906 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011907 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011908 break;
11909
11910 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011911 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011912 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011913 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011914 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011915 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011916
11917 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011918 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011919 diag::err_ovl_deleted_object_call)
11920 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011921 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011922 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011923 << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011924 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011925 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011926 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011927
Douglas Gregorff331c12010-07-25 18:17:45 +000011928 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011929 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011930
John McCall5acb0c92011-10-17 18:40:02 +000011931 UnbridgedCasts.restore();
11932
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011933 if (Best->Function == nullptr) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011934 // Since there is no function declaration, this is one of the
11935 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011936 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011937 = cast<CXXConversionDecl>(
11938 Best->Conversions[0].UserDefined.ConversionFunction);
11939
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011940 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11941 Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011942 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11943 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011944 assert(Conv == Best->FoundDecl.getDecl() &&
11945 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011946 // We selected one of the surrogate functions that converts the
11947 // object parameter to a function pointer. Perform the conversion
11948 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011949
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011950 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011951 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011952 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11953 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011954 if (Call.isInvalid())
11955 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011956 // Record usage of conversion in an implicit cast.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011957 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11958 CK_UserDefinedConversion, Call.get(),
11959 nullptr, VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011960
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011961 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011962 }
11963
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011964 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011965
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011966 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11967 // that calls this method, using Object for the implicit object
11968 // parameter and passing along the remaining arguments.
11969 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011970
11971 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011972 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011973 return ExprError();
11974
Chandler Carruth6df868e2010-12-12 08:17:55 +000011975 const FunctionProtoType *Proto =
11976 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011977
Stephen Hines651f13c2014-04-23 16:59:28 -070011978 unsigned NumParams = Proto->getNumParams();
Mike Stump1eb44332009-09-09 15:08:12 +000011979
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011980 DeclarationNameInfo OpLocInfo(
11981 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11982 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011983 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011984 HadMultipleCandidates,
11985 OpLocInfo.getLoc(),
11986 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011987 if (NewFn.isInvalid())
11988 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011989
Benjamin Kramer7034fae2013-09-25 13:10:11 +000011990 // Build the full argument list for the method call (the implicit object
11991 // parameter is placed at the beginning of the list).
Stephen Hines651f13c2014-04-23 16:59:28 -070011992 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer7034fae2013-09-25 13:10:11 +000011993 MethodArgs[0] = Object.get();
11994 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11995
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011996 // Once we've built TheCall, all of the expressions are properly
11997 // owned.
Stephen Hines651f13c2014-04-23 16:59:28 -070011998 QualType ResultTy = Method->getReturnType();
John McCallf89e55a2010-11-18 06:31:45 +000011999 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12000 ResultTy = ResultTy.getNonLValueExprType(Context);
12001
Benjamin Kramer7034fae2013-09-25 13:10:11 +000012002 CXXOperatorCallExpr *TheCall = new (Context)
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012003 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer7034fae2013-09-25 13:10:11 +000012004 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12005 ResultTy, VK, RParenLoc, false);
12006 MethodArgs.reset();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000012007
Stephen Hines651f13c2014-04-23 16:59:28 -070012008 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson07d68f12009-10-13 21:49:31 +000012009 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012010
Douglas Gregor518fda12009-01-13 05:10:00 +000012011 // We may have default arguments. If so, we need to allocate more
12012 // slots in the call for them.
Stephen Hines651f13c2014-04-23 16:59:28 -070012013 if (Args.size() < NumParams)
12014 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000012015
Chris Lattner312531a2009-04-12 08:11:20 +000012016 bool IsError = false;
12017
Douglas Gregorf9eb9052008-11-19 21:05:33 +000012018 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000012019 ExprResult ObjRes =
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012020 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley429bb272011-04-08 18:41:53 +000012021 Best->FoundDecl, Method);
12022 if (ObjRes.isInvalid())
12023 IsError = true;
12024 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000012025 Object = ObjRes;
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012026 TheCall->setArg(0, Object.get());
Chris Lattner312531a2009-04-12 08:11:20 +000012027
Douglas Gregorf9eb9052008-11-19 21:05:33 +000012028 // Check the argument types.
Stephen Hines651f13c2014-04-23 16:59:28 -070012029 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000012030 Expr *Arg;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000012031 if (i < Args.size()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000012032 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000012033
Douglas Gregor518fda12009-01-13 05:10:00 +000012034 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000012035
John McCall60d7b3a2010-08-24 06:29:42 +000012036 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000012037 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000012038 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000012039 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000012040 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012041
Anders Carlsson3faa4862010-01-29 18:43:53 +000012042 IsError |= InputInit.isInvalid();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012043 Arg = InputInit.getAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000012044 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000012045 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000012046 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12047 if (DefArg.isInvalid()) {
12048 IsError = true;
12049 break;
12050 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012051
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012052 Arg = DefArg.getAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000012053 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000012054
12055 TheCall->setArg(i + 1, Arg);
12056 }
12057
12058 // If this is a variadic call, handle args passed through "...".
12059 if (Proto->isVariadic()) {
12060 // Promote the arguments (C99 6.5.2.2p7).
Stephen Hines651f13c2014-04-23 16:59:28 -070012061 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012062 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12063 nullptr);
John Wiegley429bb272011-04-08 18:41:53 +000012064 IsError |= Arg.isInvalid();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012065 TheCall->setArg(i + 1, Arg.get());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000012066 }
12067 }
12068
Chris Lattner312531a2009-04-12 08:11:20 +000012069 if (IsError) return true;
12070
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000012071 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000012072
Richard Smith831421f2012-06-25 20:30:08 +000012073 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000012074 return true;
12075
John McCall182f7092010-08-24 06:09:16 +000012076 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000012077}
12078
Douglas Gregor8ba10742008-11-20 16:27:02 +000012079/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000012080/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000012081/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000012082ExprResult
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +000012083Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12084 bool *NoArrowOperatorFound) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000012085 assert(Base->getType()->isRecordType() &&
12086 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000012087
John McCall5acb0c92011-10-17 18:40:02 +000012088 if (checkPlaceholderForOverload(*this, Base))
12089 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000012090
John McCall5769d612010-02-08 23:07:23 +000012091 SourceLocation Loc = Base->getExprLoc();
12092
Douglas Gregor8ba10742008-11-20 16:27:02 +000012093 // C++ [over.ref]p1:
12094 //
12095 // [...] An expression x->m is interpreted as (x.operator->())->m
12096 // for a class object x of type T if T::operator->() exists and if
12097 // the operator is selected as the best match function by the
12098 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000012099 DeclarationName OpName =
12100 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012101 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenek6217b802009-07-29 21:53:49 +000012102 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000012103
John McCall5769d612010-02-08 23:07:23 +000012104 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000012105 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000012106 return ExprError();
12107
John McCalla24dc2e2009-11-17 02:14:36 +000012108 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12109 LookupQualifiedName(R, BaseRecord->getDecl());
12110 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000012111
12112 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000012113 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000012114 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko55431692013-05-05 00:41:58 +000012115 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000012116 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000012117
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000012118 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12119
Douglas Gregor8ba10742008-11-20 16:27:02 +000012120 // Perform overload resolution.
12121 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000012122 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000012123 case OR_Success:
12124 // Overload resolution succeeded; we'll build the call below.
12125 break;
12126
12127 case OR_No_Viable_Function:
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000012128 if (CandidateSet.empty()) {
12129 QualType BaseType = Base->getType();
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +000012130 if (NoArrowOperatorFound) {
12131 // Report this specific error to the caller instead of emitting a
12132 // diagnostic, as requested.
12133 *NoArrowOperatorFound = true;
12134 return ExprError();
12135 }
Kaelyn Uhraind4224342013-07-15 19:54:54 +000012136 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12137 << BaseType << Base->getSourceRange();
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000012138 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhraind4224342013-07-15 19:54:54 +000012139 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000012140 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000012141 }
12142 } else
Douglas Gregor8ba10742008-11-20 16:27:02 +000012143 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000012144 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000012145 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000012146 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000012147
12148 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000012149 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12150 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000012151 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000012152 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000012153
12154 case OR_Deleted:
12155 Diag(OpLoc, diag::err_ovl_deleted_oper)
12156 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000012157 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000012158 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000012159 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000012160 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000012161 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000012162 }
12163
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012164 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCall9aa472c2010-03-19 07:35:19 +000012165
Douglas Gregor8ba10742008-11-20 16:27:02 +000012166 // Convert the object parameter.
12167 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000012168 ExprResult BaseResult =
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012169 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley429bb272011-04-08 18:41:53 +000012170 Best->FoundDecl, Method);
12171 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000012172 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012173 Base = BaseResult.get();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000012174
Douglas Gregor8ba10742008-11-20 16:27:02 +000012175 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000012176 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000012177 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000012178 if (FnExpr.isInvalid())
12179 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012180
Stephen Hines651f13c2014-04-23 16:59:28 -070012181 QualType ResultTy = Method->getReturnType();
John McCallf89e55a2010-11-18 06:31:45 +000012182 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12183 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000012184 CXXOperatorCallExpr *TheCall =
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012185 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hamesbe9af122012-10-02 04:45:10 +000012186 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000012187
Stephen Hines651f13c2014-04-23 16:59:28 -070012188 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlsson15ea3782009-10-13 22:43:21 +000012189 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000012190
12191 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000012192}
12193
Richard Smith36f5cfe2012-03-09 08:00:36 +000012194/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12195/// a literal operator described by the provided lookup results.
12196ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12197 DeclarationNameInfo &SuffixInfo,
12198 ArrayRef<Expr*> Args,
12199 SourceLocation LitEndLoc,
12200 TemplateArgumentListInfo *TemplateArgs) {
12201 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000012202
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012203 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12204 OverloadCandidateSet::CSK_Normal);
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012205 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12206 /*SuppressUserConversions=*/true);
Richard Smith9fcce652012-03-07 08:35:16 +000012207
Richard Smith36f5cfe2012-03-09 08:00:36 +000012208 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12209
Richard Smith36f5cfe2012-03-09 08:00:36 +000012210 // Perform overload resolution. This will usually be trivial, but might need
12211 // to perform substitutions for a literal operator template.
12212 OverloadCandidateSet::iterator Best;
12213 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12214 case OR_Success:
12215 case OR_Deleted:
12216 break;
12217
12218 case OR_No_Viable_Function:
12219 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12220 << R.getLookupName();
12221 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12222 return ExprError();
12223
12224 case OR_Ambiguous:
12225 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12226 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12227 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000012228 }
12229
Richard Smith36f5cfe2012-03-09 08:00:36 +000012230 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000012231 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12232 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000012233 SuffixInfo.getLoc(),
12234 SuffixInfo.getInfo());
12235 if (Fn.isInvalid())
12236 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000012237
12238 // Check the argument types. This should almost always be a no-op, except
12239 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000012240 Expr *ConvArgs[2];
Richard Smith958ba642013-05-05 15:51:06 +000012241 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smith9fcce652012-03-07 08:35:16 +000012242 ExprResult InputInit = PerformCopyInitialization(
12243 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12244 SourceLocation(), Args[ArgIdx]);
12245 if (InputInit.isInvalid())
12246 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012247 ConvArgs[ArgIdx] = InputInit.get();
Richard Smith9fcce652012-03-07 08:35:16 +000012248 }
12249
Stephen Hines651f13c2014-04-23 16:59:28 -070012250 QualType ResultTy = FD->getReturnType();
Richard Smith9fcce652012-03-07 08:35:16 +000012251 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12252 ResultTy = ResultTy.getNonLValueExprType(Context);
12253
Richard Smith9fcce652012-03-07 08:35:16 +000012254 UserDefinedLiteral *UDL =
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012255 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000012256 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000012257 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12258
Stephen Hines651f13c2014-04-23 16:59:28 -070012259 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smith9fcce652012-03-07 08:35:16 +000012260 return ExprError();
12261
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012262 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smith9fcce652012-03-07 08:35:16 +000012263 return ExprError();
12264
12265 return MaybeBindToTemporary(UDL);
12266}
12267
Sam Panzere1715b62012-08-21 00:52:01 +000012268/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12269/// given LookupResult is non-empty, it is assumed to describe a member which
12270/// will be invoked. Otherwise, the function will be found via argument
12271/// dependent lookup.
12272/// CallExpr is set to a valid expression and FRS_Success returned on success,
12273/// otherwise CallExpr is set to ExprError() and some non-success value
12274/// is returned.
12275Sema::ForRangeStatus
12276Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12277 SourceLocation RangeLoc, VarDecl *Decl,
12278 BeginEndFunction BEF,
12279 const DeclarationNameInfo &NameInfo,
12280 LookupResult &MemberLookup,
12281 OverloadCandidateSet *CandidateSet,
12282 Expr *Range, ExprResult *CallExpr) {
12283 CandidateSet->clear();
12284 if (!MemberLookup.empty()) {
12285 ExprResult MemberRef =
12286 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12287 /*IsPtr=*/false, CXXScopeSpec(),
12288 /*TemplateKWLoc=*/SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012289 /*FirstQualifierInScope=*/nullptr,
Sam Panzere1715b62012-08-21 00:52:01 +000012290 MemberLookup,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012291 /*TemplateArgs=*/nullptr);
Sam Panzere1715b62012-08-21 00:52:01 +000012292 if (MemberRef.isInvalid()) {
12293 *CallExpr = ExprError();
12294 Diag(Range->getLocStart(), diag::note_in_for_range)
12295 << RangeLoc << BEF << Range->getType();
12296 return FRS_DiagnosticIssued;
12297 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012298 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzere1715b62012-08-21 00:52:01 +000012299 if (CallExpr->isInvalid()) {
12300 *CallExpr = ExprError();
12301 Diag(Range->getLocStart(), diag::note_in_for_range)
12302 << RangeLoc << BEF << Range->getType();
12303 return FRS_DiagnosticIssued;
12304 }
12305 } else {
12306 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000012307 UnresolvedLookupExpr *Fn =
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012308 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzere1715b62012-08-21 00:52:01 +000012309 NestedNameSpecifierLoc(), NameInfo,
12310 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000012311 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000012312
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000012313 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzere1715b62012-08-21 00:52:01 +000012314 CandidateSet, CallExpr);
12315 if (CandidateSet->empty() || CandidateSetError) {
12316 *CallExpr = ExprError();
12317 return FRS_NoViableFunction;
12318 }
12319 OverloadCandidateSet::iterator Best;
12320 OverloadingResult OverloadResult =
12321 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12322
12323 if (OverloadResult == OR_No_Viable_Function) {
12324 *CallExpr = ExprError();
12325 return FRS_NoViableFunction;
12326 }
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000012327 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012328 Loc, nullptr, CandidateSet, &Best,
Sam Panzere1715b62012-08-21 00:52:01 +000012329 OverloadResult,
12330 /*AllowTypoCorrection=*/false);
12331 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12332 *CallExpr = ExprError();
12333 Diag(Range->getLocStart(), diag::note_in_for_range)
12334 << RangeLoc << BEF << Range->getType();
12335 return FRS_DiagnosticIssued;
12336 }
12337 }
12338 return FRS_Success;
12339}
12340
12341
Douglas Gregor904eed32008-11-10 20:40:00 +000012342/// FixOverloadedFunctionReference - E is an expression that refers to
12343/// a C++ overloaded function (possibly with some parentheses and
12344/// perhaps a '&' around it). We have resolved the overloaded function
12345/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000012346/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000012347Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000012348 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000012349 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000012350 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12351 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000012352 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000012353 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012354
Douglas Gregor699ee522009-11-20 19:42:02 +000012355 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012356 }
12357
Douglas Gregor699ee522009-11-20 19:42:02 +000012358 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000012359 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12360 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012361 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000012362 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000012363 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000012364 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000012365 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000012366 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012367
12368 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000012369 ICE->getCastKind(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012370 SubExpr, nullptr,
John McCall5baba9d2010-08-25 10:28:54 +000012371 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012372 }
12373
Douglas Gregor699ee522009-11-20 19:42:02 +000012374 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000012375 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000012376 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000012377 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12378 if (Method->isStatic()) {
12379 // Do nothing: static member functions aren't any different
12380 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000012381 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -070012382 // Fix the subexpression, which really has to be an
John McCallf7a1a742009-11-24 19:00:30 +000012383 // UnresolvedLookupExpr holding an overloaded member function
12384 // or template.
John McCall6bb80172010-03-30 21:47:33 +000012385 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12386 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000012387 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000012388 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000012389
John McCallba135432009-11-21 08:51:07 +000012390 assert(isa<DeclRefExpr>(SubExpr)
12391 && "fixed to something other than a decl ref");
12392 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12393 && "fixed to a member ref with no nested name qualifier");
12394
12395 // We have taken the address of a pointer to member
12396 // function. Perform the computation here so that we get the
12397 // appropriate pointer to member type.
12398 QualType ClassType
12399 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12400 QualType MemPtrType
12401 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12402
John McCallf89e55a2010-11-18 06:31:45 +000012403 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12404 VK_RValue, OK_Ordinary,
12405 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000012406 }
12407 }
John McCall6bb80172010-03-30 21:47:33 +000012408 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12409 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000012410 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000012411 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012412
John McCall2de56d12010-08-25 11:45:40 +000012413 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000012414 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000012415 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000012416 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012417 }
John McCallba135432009-11-21 08:51:07 +000012418
12419 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000012420 // FIXME: avoid copy.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012421 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCallf7a1a742009-11-24 19:00:30 +000012422 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000012423 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12424 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000012425 }
12426
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000012427 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12428 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000012429 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000012430 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000012431 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000012432 ULE->getNameLoc(),
12433 Fn->getType(),
12434 VK_LValue,
12435 Found.getDecl(),
12436 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000012437 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000012438 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12439 return DRE;
John McCallba135432009-11-21 08:51:07 +000012440 }
12441
John McCall129e2df2009-11-30 22:42:35 +000012442 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000012443 // FIXME: avoid copy.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012444 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCallaa81e162009-12-01 22:10:20 +000012445 if (MemExpr->hasExplicitTemplateArgs()) {
12446 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12447 TemplateArgs = &TemplateArgsBuffer;
12448 }
John McCalld5532b62009-11-23 01:53:49 +000012449
John McCallaa81e162009-12-01 22:10:20 +000012450 Expr *Base;
12451
John McCallf89e55a2010-11-18 06:31:45 +000012452 // If we're filling in a static method where we used to have an
12453 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000012454 if (MemExpr->isImplicitAccess()) {
12455 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000012456 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12457 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000012458 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000012459 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000012460 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000012461 MemExpr->getMemberLoc(),
12462 Fn->getType(),
12463 VK_LValue,
12464 Found.getDecl(),
12465 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000012466 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000012467 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12468 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000012469 } else {
12470 SourceLocation Loc = MemExpr->getMemberLoc();
12471 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000012472 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000012473 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000012474 Base = new (Context) CXXThisExpr(Loc,
12475 MemExpr->getBaseType(),
12476 /*isImplicit=*/true);
12477 }
John McCallaa81e162009-12-01 22:10:20 +000012478 } else
John McCall3fa5cae2010-10-26 07:05:15 +000012479 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000012480
John McCallf5307512011-04-27 00:36:17 +000012481 ExprValueKind valueKind;
12482 QualType type;
12483 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12484 valueKind = VK_LValue;
12485 type = Fn->getType();
12486 } else {
12487 valueKind = VK_RValue;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070012488 type = Context.BoundMemberTy;
12489 }
12490
12491 MemberExpr *ME = MemberExpr::Create(
12492 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12493 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12494 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12495 OK_Ordinary);
12496 ME->setHadMultipleCandidates(true);
12497 MarkMemberReferenced(ME);
12498 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000012499 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012500
John McCall3fa5cae2010-10-26 07:05:15 +000012501 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000012502}
12503
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012504ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000012505 DeclAccessPair Found,
12506 FunctionDecl *Fn) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012507 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor20093b42009-12-09 23:02:17 +000012508}